I'm trying to run this program where a character array is created and allocated memory dynamically. Later the array elements are populated with the string "hello" for 10 consecutive locations. The values are assigned to the string elements using strdup() function call.
Once all the elements are assigned the elements are freed up in the while loop.When I run the program in the Visual Studio, the program crashes after the last pointer to the char array is freed. I believe the termination condition for the while loop is correct. But I'm not able to identify what exactly is causing the issue.
Code:
char **p;
int i;
p = malloc(10 * sizeof(char *));
for (i = 0; i < 10; i++) {
p[i] = strdup(“hello”);
}
while (*p) {
free(*p++);
}
If you want very much to use your while loop then you should write the code the following way
char **p;
int i;
p = malloc(11 * sizeof(char *));
for (i = 0; i < 10; i++) {
p[i] = strdup(“hello”);
}
p[i] = NULL;
while (*p) {
free(*p++);
}
Take into account that you need also to free the initial value of p itself. So the correct code with the while loop could look like
char **p;
int i;
p = malloc(11 * sizeof(char *));
for (i = 0; i < 10; i++) {
p[i] = strdup(“hello”);
}
p[i] = NULL;
char **q = p;
while (*q) {
free(*q++);
}
free( p );