I get a segmentation fault after free
ing 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?
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.
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)
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).
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.
If you didn't malloc()
it, you can't free()
it. Where does studentDB->name
come from?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With