dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: [C] problem with free()

  1. #1
    Join Date
    May 2003
    Location
    Italy
    Posts
    25

    [C] problem with free()

    Hi,

    i have a list which is my p, this list could have lot of elements.

    I use this code below to free the memory at the end of my program.

    A strange things happen, at certain point i dont know why, the execution stop at the free(app);

    I have this problem just on Windows! On linux every thing is fine

    Does someone know what can cause this stop problem?

    Code:
    while(p!=NULL){
    		app=p;
                    free(app);
    		p=p->next;
    
    
    	}
    thanks

  2. #2
    Join Date
    May 2008
    Posts
    96

    Re: [C] problem with free()

    Does
    Code:
    while (p != NULL) {
      app = p;
      p = p->next;
      free( app );
      }
    fix it?

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: [C] problem with free()

    It looks like you used free(app) a little too early. It should probably be:
    Code:
    while(p!=NULL){
        app=p;
        p=p->next;
        free(app);
    }
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  4. #4
    Join Date
    May 2003
    Location
    Italy
    Posts
    25

    Re: [C] problem with free()

    thanks a lot i was going crazy

  5. #5
    Join Date
    Jul 2008
    Posts
    5

    Re: [C] problem with free()

    may be freeing it reverse help

  6. #6
    Join Date
    May 2007
    Location
    Bangalore India
    Posts
    262

    Re: [C] problem with free()

    Quote Originally Posted by Navimel

    Code:
    while(p!=NULL){
    		app=p;
    	                    free(app);
    		p=p->next;
    
    
    	}
    Idea is when app=p; both are pointing to the same memory location.

    and now you do free(app) hence memory pointed by app will be gone.
    Since p also points to the same memory, hence memory pointed by p is also gone making it a dangling pointer and then you are trying to access the memory which no longer exists through the dangling pointer p.. Which lead to an UB and most likely a crash..
    Dont forget to rate my post if you find it useful.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)