How can I free all allocated memory at once?

20,028

Solution 1

No there is not. Memory which is separately allocated must be separately freed.

The only way you could free it as once is if you allocated it at once is a giant block. You would then have to do a bit of pointer math to assign every row the correct index into the array but it's not terribly difficult. This approach does have a few downsides though

  1. Extra pointer math
  2. Requires one giant contiguous block of memory vs. N smaller blocks of memory. Can be an issue in low memory or high fragmentation environments.
  3. Extra work for no real stated gain.

Solution 2

If you want to release it all at once, you have to allocate it all at once.

A simple manual solution, if you know the total size you'll need in advance, is to allocate it all in once chunk and index into it as appropriate. If you don't know the size in advance you can use realloc to grow the memory, so long as you only access it indexed from the initial pointer, and don't store additional pointers anywhere.

That being said, direct allocation and deallocation is a simple solution, and harder to get wrong than the alternatives. Unless the loop to deallocate is causing you real difficulties, I would stick with what you have.

Share:
20,028
T.T.T.
Author by

T.T.T.

Updated on April 27, 2020

Comments

  • T.T.T.
    T.T.T. about 4 years

    Here is what I am working with:

    char* qdat[][NUMTBLCOLS];
    char** tdat[];
    char* ptr_web_data;
    
        // Loop thru each table row of the query result set
        for(row_index = 0; row_index < number_rows; row_index++)
        {
            // Loop thru each column of the query result set and extract the data
            for(col_index = 0; col_index < number_cols; col_index++)
            {
                ptr_web_data = (char*) malloc((strlen(Data) + 1) * sizeof(char));
                memcpy (ptr_web_data, column_text, strlen(column_text) + 1);
                qdat[row_index][web_data_index] = ptr_web_data;
            }
         }
    
        tdat[row_index] = qdat[col_index];
    

    After the data is used, the memory allocated is released one at a time using free().

    for(row_index = 0; row_index < number_rows; row_index++)
    { 
      // Loop thru all columns used
      for(col_index = 0; col_index < SARWEBTBLCOLS; col_index++)
      {
        // Free memory block pointed to by results set array
        free(tdat[row_index][col_index]);
      }
    
    }
    

    Is there a way to release all the allocated memory at once, for this array?

    Thank You.