Thread: about realloc

  1. #1
    Registered User
    Join Date
    Mar 2007
    Posts
    33

    about realloc

    Hello!

    I have some doubts about "realloc". I've read the man file but I'm not sure about a few of things:

    - Does realloc initializate (I'm spanish I don't know if it is well write) the new space of memory??
    - If I use realloc like this:

    Code:
    ptr = calloc(50,sizeof(char));
    ptr = realloc(ptr, 100);
    Then ptr will point to the new allocated memory or to the first positon of the array??

    Thank you for your help

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Does realloc initializate (I'm spanish I don't know if it is well write) the new space of memory??
    No. The allocated memory will contain whatever random garbage was in it before realloc() was called.

    Then ptr will point to the new allocated memory or to the first positon of the array??
    It will point to the beginning of the array.
    Last edited by itsme86; 04-20-2007 at 01:36 AM.
    If you understand what you're doing, you're not learning anything.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,764
    > Does realloc initializate (I'm spanish I don't know if it is well write) the new space of memory??
    The smaller of the 'old size' or the 'new size' is preserved.

    > ptr = realloc(ptr, 100);
    Don't assign the result to the same pointer. If realloc fails, it returns NULL, but the old memory is NOT freed (but you have lost the pointer to it, so it is a leak).
    Always do something like
    Code:
    void *temp = realloc( ptr, 100 );
    if ( temp != NULL ) {
        // success
        ptr = temp;
    } else {
        // some error action
        free( ptr );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. did i understood right this explantion of realloc..
    By transgalactic2 in forum C Programming
    Replies: 3
    Last Post: 10-24-2008, 07:26 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 05:00 PM
  4. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 04:40 PM
  5. Realloc inappropriate for aligned blocks - Alternatives?
    By zeckensack in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 02:10 PM