I am having trouble understanding when to free a pointer to a pointer. For arrays, I understand that something like:
char **mat = (char**) malloc(sizeof(char*) * 100);
for(int i = 0; i < 500; i++)
mat[i] = (char*) malloc(sizeof(char) * 50);
Would require
- Freeing each ith member of the mat variable, followed by a final free call to its root (the mat**). This intuitively make sense because each malloc gets a free.
However, when I do something like so:
char *str = (char *) malloc(100 * sizeof(char));
char **pstr = &str;
free(pstr);
I find this tells me I'm attempting to free an invalid pointer. My logic is if pstr
is a pointer to a pointer to a malloc'd character array - freeing pstr
should free str
. Instead, I get an invalid pointer. What gives?