views:

281

answers:

7

I get a segmentation fault after freeing a certain pointer:

free(studentDB->name);

I can get its value without any errors or warnings:

printf("[DBG] studentDB->name: %s\n", studentDB->name);

However, as I said, the program crashes when I try to free it. What are the most common causes for a free command leading to a segmentation fault?

+6  A: 

If you didn't malloc() it, you can't free() it. Where does studentDB->name come from?

Carl Norum
Or you try to free it twice. More common, I think.
Spot on. It was a pointer, but I hadn't used `malloc` to allocate memory for it.
Pieter
+1  A: 

You've probably either free()'ed it already, or overwritten the malloc info preceding the block with a buffer overrun

Arthur Kalliokoski
A: 

A segfault from free can be caused by calling it on a pointer that was not allocated with malloc, or had been free'd already.

It would help if you posted the code where studentDB->name was allocated.

Kyle Lutz
A: 

Usually heap corruption somewhere else in the program. The heap is usually continous and the heap manager surrounds heap blocks with headers to track the blocks- If you overwrite the header of the block, access to it is fine, but free is most likely to fail.

Alexander Gessler
A: 

Has studentDB->name being allocated previously? If you did not allocate memory for that field, chances are when you called free, you end up with a seg-fault! Please check on that field and make sure it has being mallocd or strdupd.

Or that there is a corruption elsewhere on the heap, that coincided with this as you rightly pointed out you can see the value of name...

Hope this helps, Best regards, Tom.

tommieb75
A: 

Could also be that accessing the name member of the studentDB pointer is a segfault if studentDB is NULL.

Platinum Azure
A: 

From manpage:

free( ptr ) frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

One can also check:

  1. Is studentDB a non-NULL pointer to a class/struct containing a member "name"?
  2. Is the space pointed to by studentDB->name was returned by malloc/calloc/realloc?
ArunSaha