views:

167

answers:

4

What are some of the general reasons for Memory Leakage and Segmentation Fault kind of errors ?

+2  A: 

Memory Leaks: Generally this refers to a language like C where you manage the memory manually. In this case you would be allocating memory without freeing it up when you are done using it. The allocations keep piling up while the application is running and the memory can't be freed until the process finishes executing. Memory Leaks (Wikipedia)

Segmentation Faults: The most common reason for this type of error is trying to access a part of memory that either doesn't exist or is outside of the allowed memory of your running program (for example if you tried to access the memory the OS is loaded in). Usually this means you are trying to use a bad pointer, so for example:

int* ptr;
...
...
...
*ptr = 5;

would cause a segfault because ptr is a null pointer (or garbage) and you have not allocated memory for the pointer to point to. Segmentation Fault (Wikipedia)

ghills
+1  A: 

Lots, including:

  • allocation of a chunk of memory and then using more than was allocated,
  • allocating memory and not freeing it,
  • not initialising data pointers correctly,
  • not initialising funciton pointers correctly,
  • calling functions with incorrect numbers or values of parameters,
  • attempting to read or write through NULL pointers,
  • linking incorrectly to libraries or to incorrect libraries.

Not all of these apply to all languages, but these are some useful things to start thinking about.

Tim
+2  A: 

Segfaults:

  • use of dangling pointers: Not resetting pointers after deallocation
  • not checking a pointer before use
  • not initializing variables/members

Memory/resource leaks:

  • forgetting to release the resource (free memory, close file, ...)
  • in environments with garbage collector: creating a ring of referencing objects

How to detect/avoid:

  • dangling pointers: coding rule, strictly reset pointers after deallocation
  • use a static code checker for avoiding most segfaults
  • use a dynamic code analyser to verify the resource leaks are away
jdehaan
A: 

See Effective C++ series in Addison Wesley, very good for exactly the issue at hand. Note that in pointer use one has to delete individually all of the elements then del the pointer - requires skill and is often incorrectly, leading to hidden errors that do not show up easily. The other posters have the answers, I am only adding an additional detail.

Nicholas Jordan