Thread: free(ptr); question?

  1. #1
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38

    free(ptr); question?

    Hello, once again today is devoted to the pointers lesson! Now I have compiled everything successfully on the lesson so far except for the function
    Code:
    free(ptr);
    here is what I have so far that compiles.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
     int x,*p=malloc(sizeof(*p));
     p=&x;
     printf("Enter a value for x:");
     scanf("%d",&x);
     printf("this is the output of *p:%d\n",*p);
     free(p);
     getchar();
    }
    but when I run the program I get this
    Code:
    beatzz@AMD2500:~/c$ gcc -o pointers pointers.c
    beatzz@AMD2500:~/c$ ./pointers
    Enter a value for x:3
    this is the output of *p:3
    *** glibc detected *** ./pointers: free(): invalid pointer: 0xbfb8e150 ***
    ======= Backtrace: =========
    /lib/tls/i686/cmov/libc.so.6[0xb7e16a85]
    /lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7e1a4f0]
    ./pointers[0x80484a9]
    /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7dc1450]
    ./pointers[0x80483e1]
    ======= Memory map: ========
    08048000-08049000 r-xp 00000000 08:01 3801091    /home/beatzz/c/pointers
    08049000-0804a000 rw-p 00000000 08:01 3801091    /home/beatzz/c/pointers
    0804a000-0806b000 rw-p 0804a000 00:00 0          [heap]
    b7c00000-b7c21000 rw-p b7c00000 00:00 0
    b7c21000-b7d00000 ---p b7c21000 00:00 0
    b7daa000-b7dab000 rw-p b7daa000 00:00 0
    b7dab000-b7ef4000 r-xp 00000000 08:01 12289040   /lib/tls/i686/cmov/libc-2.7.so
    b7ef4000-b7ef5000 r--p 00149000 08:01 12289040   /lib/tls/i686/cmov/libc-2.7.so
    b7ef5000-b7ef7000 rw-p 0014a000 08:01 12289040   /lib/tls/i686/cmov/libc-2.7.so
    b7ef7000-b7efa000 rw-p b7ef7000 00:00 0
    b7efd000-b7f07000 r-xp 00000000 08:01 12271638   /lib/libgcc_s.so.1
    b7f07000-b7f08000 rw-p 0000a000 08:01 12271638   /lib/libgcc_s.so.1
    b7f08000-b7f0c000 rw-p b7f08000 00:00 0
    b7f0c000-b7f0d000 r-xp b7f0c000 00:00 0          [vdso]
    b7f0d000-b7f27000 r-xp 00000000 08:01 12271629   /lib/ld-2.7.so
    b7f27000-b7f29000 rw-p 00019000 08:01 12271629   /lib/ld-2.7.so
    bfb7b000-bfb90000 rw-p bffeb000 00:00 0          [stack]
    Aborted
    Did I make a mistake? or am I missing libraries?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    it should crash

    p=&x;

    address returned by malloc is overwritten with the address of x

    when you call free(p) - you pass the address malloc has no idea about. So you get a crash here
    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

  3. #3
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38
    so how dose one appropriately use free(); ?

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by elsheepo View Post
    so how dose one appropriately use free(); ?
    give to free exactly the same address as received from malloc
    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

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    If you want a pointer to point to a variable on the stack, don't allocate any space:

    Code:
    int n;
    int* p;
    p = &n;
    /*no free*/
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38
    I understand what anon is saying, just leave the malloc out, and it would work fine, but I'm trying to use it just for the tutorials sake.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
     int x,*p=malloc(sizeof(*p));
     p=&x;
     printf("Enter a value for x:");
     scanf("%d",&x);
     printf("this is the output of *p:%d\n",*p);
     free(p);
     getchar();
    }
    by "give to free exactly the same address as received from malloc" do you mean by changing this, free(p); to this free(*p); because I tried that and it wouldn't even compile.
    Last edited by elsheepo; 02-01-2009 at 10:35 AM.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No, more like:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int x;
        int *p = malloc(sizeof(*p));
        printf("Enter a value for x:");
        scanf("%d", &x);
        *p = x; /* Assume that malloc() did not return a null pointer. */
        printf("this is the output of *p: %d\n", *p);
        free(p);
        getchar();
        return 0;
    }
    Though in this case the dynamic memory allocation is not useful since just using x will suffice.
    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

  8. #8
    The larch
    Join Date
    May 2006
    Posts
    3,573
    A pointer can refer to an int on the stack (int x) or it can point to a int that is allocated dynamically. With malloc you ask for enough memory to store an int in, and p is the only means that allows you to access it.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
     int *p=malloc(sizeof(*p));
     printf("Enter a value to be stored:");
     scanf("%d",p);
     printf("this is the output of *p:%d\n",*p);
     free(p);
     getchar();
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  9. #9
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38
    okay, I got the program to work the way I wanted it to at least. I'm not sure if I fully understand pointers at the moment, but I supose with time I will. Thanks for the help guys
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
     int x,*p=malloc(sizeof(*p));
     printf("Enter a value for x:");
     scanf("%d",&x);
     *p=x;
     printf("this is the output of *p:%d\n",*p);
     free(p);
     getchar();
    }
    for some reason the program works just the same without
    Code:
    return 0;
    but thanks lazerlight for your example, it worked

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by elsheepo View Post
    for some reason the program works just the same without
    Code:
    return 0;
    but thanks lazerlight for your example, it worked
    Yes, it would do - except that any program askign your program whether it was successful or not would get an answer that may be just about anything, as the return value from a function that doesn't have a return statement will be whatever happens to be in the register that the compiler designates "the return value" - in your case, it would probably be the return value from getchar(), but that is not guaranteed.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38
    so is it a good idea to have
    Code:
    return 0;
    in all functions?

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by elsheepo View Post
    so is it a good idea to have
    Code:
    return 0;
    in all functions?
    Yes. Unless of course something went wrong (e.g. the application could not open a file, ran out of memory, or the user input was invalid), in which case you may want to return some other number to indicate "not a success". By convention, successfull execution of the program should return 0 - other times, return non-zero. You may even return different things to indicate WHY it went wrong.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    To add to that, you really should explicitly specify the return type of all functions, including main. Omitting return types is an error in C99 and C++ (and deprecated in C90).
    And as for pointers, remember this:
    A pointer is a variable that stores memory addresses. Thus, when assigning a value to it, you are overwriting its contents--its address.
    * is the dereference operator. It basically tells the compiler "go to the address stored inside this variable and do x"

    The function free relies on that the address passed in is an address that was returned by malloc. If it is not, you can expect bad consequences.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Mar 2008
    Location
    NE Washinton
    Posts
    38
    Quote Originally Posted by Elysia View Post
    you really should explicitly specify the return type of all functions,
    1. Dose that mean when declaring a function such as "main()" I should write it "int main()"?
    2. Is "free()" only used in conjunction with"malloc(sizeof())"?
    3. Can someone please explain these steps that were taken to fix the program?

    Bugged code
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
     int x,*p=malloc(sizeof(*p));
     p=&x;
     printf("Enter a value for x:");
     scanf("%d",&x);
     printf("this is the output of *p:%d\n",*p);
     free(p);
     getchar();
    }
    Fixed code
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int x;
        int *p = malloc(sizeof(*p));
        printf("Enter a value for x:");
        scanf("%d", &x);
        *p = x; /* Assume that malloc() did not return a null pointer. */
        printf("this is the output of *p: %d\n", *p);
        free(p);
        getchar();
        return 0;
    }
    3a. "main()" was changed to "int main()"

    3b. Notice she separated the variables during declaration, even though they are both integers. Is this necessary or just personal preference?

    3c. "p=&x;" was changed to "*p=x;" also moved below scanf why?

    3d. "return 0;" was used, I think I understand that one now.
    Last edited by elsheepo; 02-03-2009 at 09:10 AM.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by elsheepo
    1. Dose that mean when declaring a function such as "main()" I should write it "int main()"?
    Yes. Of course, if the function returns an object of some other type then you should declare it with the appropriate return type, or void if the function does not return any value at all.

    Quote Originally Posted by elsheepo
    2. Is "free()" only used in conjunction with"malloc(sizeof())"?
    It can be used in conjunction with realloc() as well. The sizeof is useful but not essential here.

    Quote Originally Posted by elsheepo
    3a. Notice she separated the variables during declaration, even though they are both integers. Is this nessisary or just personal preference?
    Personal preference. It can be clearer to have declarations, especially those involving pointers, on their own lines.

    Quote Originally Posted by elsheepo
    3b. p=&x; was changed to *p=x; also moved below scanf why?
    The change from p = &x; to *p = x; is the "fix". The move to just below scanf() is not important.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Question about linked lists.
    By cheeisme123 in forum C++ Programming
    Replies: 6
    Last Post: 02-25-2003, 01:36 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM