Thread: Environment variable corruption

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    .
    Join Date
    Nov 2003
    Posts
    307
    There are several malloc implementations - a malloc implementation also covers free() (or new and delete. Whichever applies.) malloc looks for the first memory chunk in the free list that is big enough to accomodate your request.
    Code:
    free(path);   <- this frees up a chunk at least 12 (+4) bytes long
    .............
    dirPtr=malloc(5); <- this needs only five (+4) bytes, so it re-uses the memory
    The +4 is there because malloc creates a memory descriptor that is two unsigned longs (each long is usually 4 bytes in 32 bit image files, check limits.h for your particular box - see LONG_MAX )

    The first long is the size, the second longword is the address that malloc returns. So, if you malloc(120), the algorithm looks for the first 124 byte-long free chunk.
    (This is how Doug Lea's malloc works, for example)

    It also explains your observation - malloc is re-using your memory. Which observation is a bad idea by the way. Don't free() the path variable.

    Period.

  2. #2
    Registered User
    Join Date
    Jan 2004
    Posts
    22
    Thanks for the replies. After testing, I see that not freeing the variable creates a memory leak. I call the test function in a loop and it eventually gives me a memory error, I suspect since I'm not freeing "path". Here is the test code:
    Code:
    void setpath()
    {
        char *path;
    
        path = (char *)malloc(13);
        if (path == 0)
    	printf("Memory allocation error.\n");
            
        strcpy(path, "NEWPATH=test");
    
        putenv(path);
    }
    Last edited by miclus; 10-01-2004 at 12:39 AM.

  3. #3
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    free the previous path before setting the new one then.
    Code:
    void setpath()
    {
        static char *path = NULL;
    
        if( path != NULL )
            free( path );
    
        path = (char *)malloc(13);
        if (path == 0)
    	printf("Memory allocation error.\n");
            
        strcpy(path, "NEWPATH=test");
    
        putenv(path);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  2. which variable can store words?
    By Hunterofman in forum C++ Programming
    Replies: 8
    Last Post: 04-28-2008, 05:59 PM
  3. global and static variable in a class delivered in a DLL
    By George2 in forum C++ Programming
    Replies: 16
    Last Post: 04-13-2008, 08:19 AM
  4. Retrieving PATH Environment Variable
    By mercury529 in forum Windows Programming
    Replies: 9
    Last Post: 01-09-2007, 08:02 PM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM