[prog] free() troubles, pointer arrays

John Stoneham lyric.list.lc-programming at lyrically.net
Wed Mar 17 19:08:07 EST 2004


> char ** main_ptr;
>
> for(i=0; i<max_rows; i++)
>    free(*main_ptr[i]);

I'd say you're lucky this runs at all, and it's probably likely to crash at
some point.

main_ptr is a char** - it's a pointer to a pointer (or the first of an array
of pointers). The expression main_ptr[i] follows the first pointer via the []
notation and thus yields a char *. Following that char * with the * deference
operator thus yields a char, which you're then attempting to free. That's why
the error message.

I expect you meant to write:

free(main_ptr[i]);

Alternatively, you could use pointer arithmetic and write:

free(*(main_ptr + i));

which is exactly equivalent. (Just remember that [] is shorthand for pointer
add + deference.)

Hope this helps,

- John


More information about the Programming mailing list