Thread: Dynamic memory allocation

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by awsdert
    That's not the kinda cleanup I was referring to
    hamster_nz was replying to Nwb, as you can see from the quote. You should read hamster_nz's post #12 instead.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Tip, works with GCC, CLANG and Intel C++ Compiler (but I'm not sure of __attribute__ syntax there... probably __declspec):

    Code:
    void cleanup_str( char **p ) { free( *p ); }
    ...
    /* Some function */
    {
      char *s __attribute__((cleanup(cleanup_str))) = NULL;
    
      if ( asprintf( &s, "blablabla: %s = %d\n", str, i ) < 0 )
        return 0;  // exit the scope. cleanup_str is called.
    
      ... use s pointer here...
    }
    ... out of scope... cleanup_str() is called.

  3. #18
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,733
    Quote Originally Posted by laserlight View Post
    hamster_nz was replying to Nwb, as you can see from the quote. You should read hamster_nz's post #12 instead.
    Yeah that was my mistake for not noticing, doesn't change the validity of what I said, haphazard is after all not what I was going for with maintaining a list of buffers during the life time of the app

  4. #19
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,733
    Quote Originally Posted by flp1969 View Post
    Tip, works with GCC, CLANG and Intel C++ Compiler (but I'm not sure of __attribute__ syntax there... probably __declspec):

    Code:
    void cleanup_str( char **p ) { free( *p ); }
    ...
    /* Some function */
    {
      char *s __attribute__((cleanup(cleanup_str))) = NULL;
    
      if ( asprintf( &s, "blablabla: %s = %d\n", str, i ) < 0 )
        return 0;  // exit the scope. cleanup_str is called.
    
      ... use s pointer here...
    }
    ... out of scope... cleanup_str() is called.
    That's certainly an interesting way to do it, I prefer explicit calls though, even if that means creating a struct to put all the variables in that need cleanup and just pass it onto a single function which calls all of them, something like:

    Code:
    struct FOO { struct A *a; struct B *b; }
    int FooReturn( struct FOO *foo, int ret )
    {
      if( foo->a )
        free( foor->a );
    
      if ( foo->b )
        free( foor->b );
    
      return ret;
    }
    
    int FooReportAndReturn( FILE *file, char *path, uint line, struct FOO *foo, int err )
    {
      fprintf( file, "%f:%u: Error 0x%08X (%u) '%s'", path, line, err, err, strerror( err ) );
      return FooReturn( foo, err );
    }
    
    #define FooMacroReportAndReturn( FOO, ERR ) FooReportAndReturn( stderr, __FILE__, __LINE__, FOO, ERR )
    
    int Foo()
    {
      int err
      struct FOO foo = {NULL};
      foo.a = malloc( sizeof(struct A);
      foo.b = malloc( sizeof(struct B);
      ....
      if ( err )
        return FooMacroReportAndReturn( &foo, err ); 
      ...
     return FooReturn( &foo, 0 );
    }
    This provides a consistent and clean way of returning when appropriate

  5. #20
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by Nwb View Post
    Is it necessary to call free() when you're about to reach program termination? The entire program is about to be unloaded anyway..
    It is always best to free any memory you have allocated using, malloc(), calloc(), or realloc(), then using valgrind under Linux, you can double check for any allocations you missed, along with other memory errors. I use valgrind on all my code.

    The other issue with free is not setting the pointer to NULL after freeing the memory. You CANNOT access the memory after freeing it up!!! A better free() can help if consistently used:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void *free2(void *ptr);
    
    int main(void)
    {
       char *ptr = NULL;
    
       ptr = malloc(100);
    
       ptr = free2(ptr);
    
       /* Can also be called as with free():
          free2(ptr);
          ptr = NULL;
       */
    
       return 0;
    }
    
    void *free2(void *ptr)
    {
        free(ptr);
        return NULL;
    }
    This is the way free() should have been defined by Dennis!

  6. #21
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by laserlight View Post
    and besides, the amount of memory available on the stack could be pretty limited.
    Did you mean to say that memory available in stack is limited compared to heap (I got this impression because the discussion was about allocating memory on the heap)?

    If so, why would that be? I had read that the stack and heap share the same memory space.. stack being at the top and growing downwards and heap being at the bottom and grouping upwards until they meet and there is no more memory left. So since they share the same memory space and grow until they can't.. they should have the same memory limit..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is dynamic memory allocation
    By dbzx in forum C Programming
    Replies: 7
    Last Post: 06-08-2009, 08:11 AM
  2. Dynamic Memory Allocation
    By schifers in forum C Programming
    Replies: 12
    Last Post: 05-14-2008, 01:49 PM
  3. Memory dynamic allocation
    By elvio.vicosa in forum C Programming
    Replies: 8
    Last Post: 10-16-2007, 03:30 AM
  4. Help with dynamic memory allocation
    By malooch in forum C Programming
    Replies: 2
    Last Post: 12-13-2006, 01:26 PM
  5. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM

Tags for this Thread