开发者

How can I free all allocated memory at once?

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.


Not with the standard malloc() allocator - you need to investigate the use of memory pools. These work by allocating a big block of memory up-front, allocating from it and freeing back to it as you request via their own allocation functions, and then freeing the whole lot with a special "deallocate all" function.

I must say I've always found these things a bit ugly - it really isn't that hard to write code that doesn't leak. The only reason I can see for using them is to mitigate heap fragmentation, if that is a real problem for you.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜