Thread: Segmentation Fault on Free()

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    15

    Question Segmentation Fault on Free()

    Hello,
    When I try to free() the following allocated memory I get segmentation fault. Why is that and how can I slove this?
    Thanks in advance.
    Code:
    typedef struct filterNode_st{
    	void* data;
    	struct filterNode_st* next;
    } filterNode;
    Code:
    unsigned int binNetIP=(binHostIP >> (32-mask));
    newNode->data=(unsigned int*)malloc(sizeof(unsigned int));
    newNode->data=(unsigned int*)binNetIP;
    Code:
    void destroyFilter(){
    	filterNode* filter=filterHead;
    	filterNode* trav=filter->next;
    	while (filter){
    		free(filter->data);   //<- This line triggers Segmentation Fault
    		trav=filter;
    		filter=filter->next;
    		free(trav);
    	}
    }
    Last edited by Stiletto; 01-25-2012 at 01:19 PM.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    344
    Quote Originally Posted by Stiletto View Post
    Hello,
    When I try to free() the following allocated memory I get segmentation fault. Why is that and how can I slove this?
    Thanks in advance.
    Code:
    typedef struct filterNode_st{
    	void* data;
    	struct filterNode_st* next;
    } filterNode;
    Code:
    unsigned int binNetIP=(binHostIP >> (32-mask));
    newNode->data=(unsigned int*)malloc(sizeof(unsigned int));
    newNode->data=(unsigned int*)binNetIP;
    You're setting data to point to malloced space and then setting it to something else on the very next line. This means that whatever space you just malloced is lost and you're trying to free something other than what you malloced.

    You need to dereference newNode->data in the second assignment so you're putting binNetIP in the newly allocated space rather than overwriting the pointer to that space.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Posts
    15
    Ofcourse. Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-12-2011, 08:28 PM
  2. Segmentation fault
    By gkoenig in forum C Programming
    Replies: 3
    Last Post: 03-01-2008, 02:14 PM
  3. segmentation fault (calloc, free)
    By kentadams in forum C Programming
    Replies: 2
    Last Post: 09-07-2007, 08:50 AM
  4. segmentation fault in free()
    By franziss in forum C Programming
    Replies: 4
    Last Post: 02-22-2005, 01:09 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM