Thread: Help C free char** array

  1. #1
    Registered User
    Join Date
    Oct 2017
    Posts
    3

    Help C free char** array

    Hi I need help optimizing this code:

    Code:
    void free_fields(char** array, int count)
    {
         SendMessage(statusBAR, SB_SETTEXT, 1,(LPARAM)"Freeing Memory");
        int i ;
    	if (count>0)
    	{
    		for (i = 0; i<count; i++ )  {
    
    
             if  (array!=NULL)  free( array[i] );
    		}
    	  if  (array!=NULL) free( array );
    	}
    	//MessageBox(NULL,"Free","Free",MB_OK | MB_ICONERROR);
    }
    It is working but with big data its slow ;
    Compiler TDM-GCC-64 -> x86_64-w64-mingw32-gcc.exe
    Same code with Pelles C its much faster but sometimes crash the application
    Thank You.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Well, you could move that if statement outside the for loop, there's no need to keep checking it after each and every iteration, just check it once at the beginning and if NULL, skip the loop entirely. Also, are you sure you didn't mean to check the individual element's pointer instead of the whole thing?
    Code:
    if  (array[i]!=NULL)  free( array[i] );
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Oct 2017
    Posts
    3
    Thank you
    Goes a little faster (still not instant but with ~300000 rows/ 6 columns I guess it takes some time to free )
    I guess I was confused because I started Project
    in Pelles C than switched to Code::Blocks .
    Pelles C gives application crashes even when compiles OK.
    Btw : Its WinAPI Virtual List with data from Sqlite.

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    You know, there's another way to minimize overhead. You could omit the free_fields() function and instead modify your alloc_fields() or whatever function to use realloc instead. Free extra memory only on demand (when the array shrinks) instead of every single time.

    Here of course I assume that you call it multiple times, which may not be the case.
    Last edited by GReaper; 10-27-2017 at 03:22 AM.
    Devoted my life to programming...

  5. #5
    Registered User
    Join Date
    Oct 2017
    Posts
    3
    I will give it a try;
    Thank You.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 03-20-2016, 05:17 AM
  2. Replies: 2
    Last Post: 09-25-2014, 06:12 AM
  3. Replies: 2
    Last Post: 09-25-2014, 04:03 AM
  4. Replies: 3
    Last Post: 11-17-2008, 12:36 PM
  5. Initializing char arrays on the free store
    By roktsyntst in forum C++ Programming
    Replies: 6
    Last Post: 12-10-2002, 06:22 AM

Tags for this Thread