Like Tree1Likes
  • 1 Post By KCfromNC

Segmentation Fault on Free()

This is a discussion on Segmentation Fault on Free() within the C Programming forums, part of the General Programming Boards category; Hello, When I try to free() the following allocated memory I get segmentation fault. Why is that and how can ...

  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 12: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.
    stahta01 likes this.

  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, 07:28 PM
  2. Segmentation fault
    By gkoenig in forum C Programming
    Replies: 3
    Last Post: 03-01-2008, 01: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, 12:09 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 10:09 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21