Thread: malloc() and free()

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    51

    malloc() and free()

    If I allocated a pointer using:

    char *ptr = malloc(1024);

    but messed around with the pointer address and such, say do this:

    ptr = ptr + 20;
    *ptr = *ptr + 100;

    if I do free(ptr), will that work? I ask this because I did change the initial memory location that ptr was malloc(ed) with, and changed its values as well.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You must pass the same pointer value to free that was returned from malloc.
    The example you posted will quite likely corrupt the heap.

    Note that the line with 100 in it is fine, as it doesn't modify the pointer value.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc calloc and free
    By -EquinoX- in forum C Programming
    Replies: 27
    Last Post: 03-26-2009, 10:59 AM
  2. Malloc - Free giving double free or corruption error
    By andrew.bolster in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 06:22 AM
  3. Replies: 12
    Last Post: 06-24-2005, 04:27 PM
  4. Ask about free funtion using with malloc
    By ooosawaddee3 in forum C++ Programming
    Replies: 1
    Last Post: 05-12-2002, 04:43 PM
  5. Malloc and Free.....
    By heljy in forum C Programming
    Replies: 5
    Last Post: 04-14-2002, 09:17 PM