C - Does freeing an array of pointers also free what they're pointing to?

前端 未结 3 2248
深忆病人
深忆病人 2020-12-08 17:53

Say I have an array of pointers to structs that contain a string each and so for something like this:

printf(\"%s\\n\", array[0]);

The outp

3条回答
  •  长情又很酷
    2020-12-08 18:17

    This all depends on how the array was allocated. I'll give examples:

    Example 1:

    char array[10];
    free(array);     // nope!
    

    Example 2:

    char *array;
    array= malloc(10);   // request heap for memory
    free(array);         // return to heap when no longer needed
    

    Example 3:

    char **array;
    array= malloc(10*sizeof(char *));
    for (int i=0; i<10; i++) {
        array[i]= malloc(10);
    }
    free(array);        // nope. You should do:
    
    for (int i=0; i<10; i++) {
        free(array[i]);
    }
    free(array);
    

    Ad. Example 1: array is allocated on the stack ("automatic variable") and cannot be released by free. Its stack space will be released when the function returns.

    Ad. Example 2: you request storage from the heap using malloc. When no longer needed, return it to the heap using free.

    Ad. Example 3: you declare an array of pointers to characters. You first allocate storage for the array, then you allocate storage for each array element to place strings in. When no longer needed, you must first release the strings (with free) and then release the array itself (with free).

提交回复
热议问题