Thread: realloc question

  1. #1
    Registered User
    Join Date
    May 2011

    realloc question

    I've been playing with pointers and dynamic memory allocation for the last couple of days. Did I get the code below right? I want ptr1 and ptr2 to point to the same memory location. I suppose the address of the memory "block" might change after the call to realloc, so I put the address in ptr1 to ptr2 again. Is that correct?

    int *ptr1, *ptr2;
    ptr1 = (int *)malloc(sizeof(int));
    ptr2 = ptr1;
    /* some code here*/
    ptr1 = realloc(ptr1, 3);
    ptr2 = ptr1; // Necessary?

  2. #2
    Join Date
    Aug 2010
    Ontario Canada
    Yes it's necessary after realloc()... as you correctly discerned, the address can/will change.

    Also beware of your malloc() calls... sizeof(int) will allocate only 4 bytes (the size of an integer variable) or as few as 2 bytes if you are in India.

  3. #3
    Registered User
    Join Date
    Nov 2004
    Yes it is necessary.
    >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about realloc
    By donthate in forum C Programming
    Replies: 2
    Last Post: 10-14-2010, 07:20 PM
  2. Realloc Quick Question.
    By killpoppop in forum C Programming
    Replies: 36
    Last Post: 01-13-2009, 01:04 PM
  3. Realloc Question
    By cstudent in forum C Programming
    Replies: 3
    Last Post: 05-17-2008, 01:32 AM
  4. question about realloc
    By thesand in forum C Programming
    Replies: 5
    Last Post: 10-29-2006, 01:45 AM
  5. Quick realloc question
    By Matt13 in forum C Programming
    Replies: 7
    Last Post: 04-02-2004, 08:40 AM