I’m trying to create a pointer to char pointer to which I can easily add new elements (strings). I use malloc to create the first 2 dimensions and realloc when I want to add new items. I wrote code with and without realloc and I’m getting the same results. Is this an expected/normal behavior?
With realloc:
char **p; // create pointer to char pointer
p = malloc(sizeof(char*) * 2); // allocate 2 dimensions
p[0] = "ab";
p[1] = "cd";
void* resizedP = (void*)realloc(p, sizeof(char*) * 4); // resize array
p = (char**)resizedP;
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);
Without realloc:
char **p;
p = malloc(sizeof(char*) * 2);
p[0] = "ab";
p[1] = "cd";
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);
It is absolutely necessary to call
realloc()to resize a memory block obtained bymalloc(). You are invoking undefined behavior by accessing beyond the bounds of the memory block that has been allocated to your program.There might be some important data right after your allocated memory block that your second code snippet will run over. And if the program even attempts to access memory blocks in another process because of an out-of-bounds error, the operating system will complain loudly (resulting in segmentation faults).
There is no guarantee that your second code snippet (without
realloc()) won’t crash or otherwise fail in the future. It just happened to work this time.