McqMate
Emily Davis
1 week ago
I'm working on a project where I need to store multiple strings using dynamic memory allocation. I'm using malloc to allocate an array of char pointers, then allocating each string with strdup. After processing, when I call free on the array and each string, it crashes with a segmentation fault. Here's a simplified version of my code:
char **arr = malloc(3 * sizeof(char *));
arr[0] = strdup("hello");
arr[1] = strdup("world");
arr[2] = strdup("test");
// ... do something ...
for (int i = 0; i < 3; i++) {
free(arr[i]);
}
free(arr);I've compiled with -g and used gdb, but I'm not sure if I'm freeing in the right order or if there's a memory corruption issue. Any tips?
Segmentation faults during memory deallocation in C are often due to incorrect usage of pointers or memory corruption. Here's a step-by-step guide to debug and fix this:
malloc or strdup didn't fail and return NULL. Always add error handling, e.g., if (arr == NULL) { /* handle error */ }.-g -fsanitize=address (if using GCC/Clang) to detect memory issues at runtime. Alternatively, use valgrind for detailed leak and error reports. Run: valgrind ./your_program.arr[i] after allocation).free on the same pointer twice.#include
#include
#include
int main() {
int size = 3;
char **arr = malloc(size * sizeof(char *));
if (arr == NULL) {
perror("malloc failed");
return 1;
}
const char *strings[] = {"hello", "world", "test"};
for (int i = 0; i < size; i++) {
arr[i] = strdup(strings[i]);
if (arr[i] == NULL) {
perror("strdup failed");
// Free already allocated memory before exiting
for (int j = 0; j < i; j++) free(arr[j]);
free(arr);
return 1;
}
}
// Process strings here
for (int i = 0; i < size; i++) {
free(arr[i]);
}
free(arr);
return 0;
}