Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault after free(), what are the common causes for this?

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?

like image 602
Pieter Avatar asked Feb 21 '10 21:02

Pieter


People also ask

Can free () cause seg fault?

Writing to freed (or out-of-scope) memory might cause a segmentation fault or corrupt data if the memory is recycled and reused. In certain cases, writing malicious data to freed memory can result in arbitrary code execution.

What are the causes of segmentation fault?

The following are some typical causes of a segmentation fault: Attempting to access a nonexistent memory address (outside process's address space) Attempting to access memory the program does not have rights to (such as kernel structures in process context) Attempting to write read-only memory (such as code segment)

What is the common issue that would cause a segmentation fault when using character strings in C?

The segfault happens when you try to change the first character to 'z' . Whenever using "%p" on printf, you should cast the pointer to void * as in printf("%p", (void *)str); When printing a size_t with printf, you should use "%zu" if using the latest C standard (C99).

How do you fix a segmentation fault?

See if your compiler or library can be set to check bounds on [i] , at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers. Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems.


1 Answers

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

like image 165
Carl Norum Avatar answered Sep 25 '22 20:09

Carl Norum