I find the splint
output to be quite unreadable. Depending on your platform, you might also want to try valgrind
.
Reglardless, the main issue with your code is that pc
is a local variable.
It becomes invalid at the end of Init()
, as it is (with probably every compilers) located on the stack.
You will probably want to do
w->o = (obj *) malloc(sizeof(obj));
instead.
An alternate way of doing this would be to change the type of o in w to obj
instead of obj *
.
Note on memory management in C
(further reading highly recommended):
Function arguments and local variables usually lie on the so-called stack
. They become invalid as soon as the function returns.
The size of stack objects always needs to be known to the compiler.
Objects that are allocated via malloc()
lie on the heap. malloc()
can be used for objects of unknown size. Objects allocated by malloc()
stay valid until their pointers are passed to realloc()
or free()
. If you forget to pass a malloc
'd pointer to free
, you have a memory leak. If you access an object after it became invalid, you'll get undefined behaviour (that place in the heap might be re-used by something else by now, but maybe the data is still there, who knows?). In the worst case you might get a segmentation fault, or a heap corruption. If you pass an invalid object pointer to free()
or realloc()
, you'll probably get a heap corruption.
Global variables and static function members lie somewhere else (tm), and valid during the whole execution of the program (at least from entering main until returning from it, like a local variable of main).
malloc()
is a complex function that internally manages available blocks of memory in a complex datastructure called the heap. A heap corruption means that you damage that datastructure itself. A segmentation fault means that you write/read somewhere outside of a valid block of memory.
Note that the C
standard does not guarantee any if this. It doesn't guarantee that something like a stack even exists. However, all compilers that I know of do it like this. For some embedded platforms though, malloc()
is a pretty simple function that just increments a pointer each time something is allocated, and free()
does nothing at all.