Thread: Free not working after malloc was used to allocate memory

  1. #1
    C Fanatic ehitam's Avatar
    Join Date
    Jun 2012
    Posts
    22

    Free not working after malloc was used to allocate memory

    Consider this program:
    Code:
    // sb_string class v1.04
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    typedef struct sb_string {
    	
    	int len;
    	char *data;
    } sb_string;
    
    
    
    
    sb_string *sb_init() {
    	
    	sb_string *str;
    	
    	str = (sb_string*) malloc(sizeof(sb_string));
    	str->len = 1;
    	str->data = NULL;
    	return str;
    }
    
    
    void sb_massacre(sb_string *target){
    	
    	
    	if (target != NULL) {
    		printf("(in_function)-before Value of len = %d\n", target->len);
    		free(target);
    		
    		printf("(in_function)-after Value of len = %d\n", target->len);
    		target = NULL;
    	}
    	
    }
    
    
    
    
    int main(int agrc, char **argv){
    	
    	sb_string *my_str;
    	
    	my_str = sb_init();
    	
    	printf("-before Value of len = %d\n", my_str->len);
    	
    	sb_massacre(my_str);
    	
    	printf("-after Value of len = %d\n", my_str->len);
    	
    	return 0;
    	
    }
    And here is the output I got:
    Code:
    [harshvardhan@hari-rudra] ~/Desktop% gcc49 -o test test.c
    [harshvardhan@hari-rudra] ~/Desktop% ./test
    -before Value of len = 1
    (in_function)-before Value of len = 1
    (in_function)-after Value of len = 1
    -after Value of len = 1
    I was trying to make a little easier to work with string. Once the memory is allocated by malloc via sb_init() function, the sb_massacre function wasn't working to deallocate the memory. I had used multiple versions of gcc and clang but the result is same.

    Really confused, what am I missing?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Do not try access a pointer after you free() it - even in code like the definition of sb_massacre(). free() does not have to work in a particular way.

    The memory is otherwise properly deallocated, but your massacre function does not update the pointer from the calling function, so it will still point to the old contents. If you want massacre() to change the calling function's pointer variable, you should do something like:

    Code:
    void sb_massacre(sb_string **target);
    
    void sb_massacre(sb_string **target)
    {
      if (target != NULL && *target != NULL)
      {
        free (*target);
        *target = NULL;
      }
    }
    
    // in a calling function such as main()...
    sb_string *my_str;     
    my_str = sb_init();
    sb_massacre(&my_str);
    After this, my_str will be NULL and further attempts to use it should segfault.

    If you are curious why you could still read the old contents, please understand that free() does not have to disassociate pointers from their old contents; the memory has to be made available for reallocation only. You can try to access the old contents of a pointer, but you don't know what will happen. It could crash or not crash the program.
    Last edited by whiteflags; 06-13-2014 at 11:11 PM.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Note that free can be freely used on a null pointer, so if you were not printing stuff from within sb_massacre (sb_free or sb_destroy would probably be more common choices for the name) when the pointer from the caller is a null pointer, you could write:
    Code:
    void sb_massacre(sb_string **target)
    {
        if (target)
        {
            free(*target);
            *target = NULL;
        }
    }
    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

  4. #4
    C Fanatic ehitam's Avatar
    Join Date
    Jun 2012
    Posts
    22
    Thank you whiteflags and laserlight! I really didn't know that free() don't disassociate from old contents. Would the freed memory would be available for reallocation by other processes and programs too or only to the current program?

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by ehitam View Post
    Would the freed memory would be available for reallocation by other processes and programs too or only to the current program?
    It depends on the impleemntation. malloc allocates memory inside some big memory chunk reserved by the process from the OS.

    After it is freed memory manager can leave big chunk reserved for next malloc, or return it to the OS (if all parts of the chunk are already freed).
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 12-28-2012, 04:07 PM
  2. Malloc failure to allocate memory
    By rsgysel in forum C Programming
    Replies: 10
    Last Post: 01-23-2010, 05:32 AM
  3. free-ing un-malloc-ed memory
    By Bladactania in forum C Programming
    Replies: 18
    Last Post: 04-27-2009, 10:13 PM
  4. free not working with malloc
    By P4R4N01D in forum Windows Programming
    Replies: 10
    Last Post: 12-19-2007, 09:08 PM
  5. How do I use malloc to allocate memory for a linked list?
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 09-14-2001, 01:02 PM