Thread: realloc problems

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    161

    realloc problems

    I use realloc to find a new memory location assign it to a pointer and copy its old data to the new location. I get NULL. I tryed to use MessageBox and itoa functions to find out the new size in bytes witch is 24bytes. I don't know why it returns NULL. I used malloc previously to allocate a poniters starting memory. Here is the line that returns NULL;

    Lines.lpLines =(char **)realloc(Lines.lpLines, sizeof(char **) * Lines.max );

    Anyone know what the problem could be?

    Thanx in advance!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Any prior use of malloc/realloc/free could have messed things up
    Any prior use of the memory returned by malloc/realloc could have messed things up here

    Look for
    - use before alloc
    - use after free
    - generally getting the size wrong - int *ptr = malloc(10) does NOT allocate space for 10 integers.

    Also, your code has the realloc assignment bug
    Code:
    char **temp = (char **)realloc(Lines.lpLines, sizeof(char **) * Lines.max );
    if ( temp != NULL ) {
        Lines.lpLines = temp;
    } else {
        // cannot realloc
        // but at least Lines.lpLines points to what we have so far
    }
    Use a temp pointer to preserve the old pointer, until you know the new one is allocated.

    You really should be using new and delete in C++.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    161
    Thanx. I got it to work properly using new and delete.

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. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 05:00 PM
  3. realloc() problems
    By DMH in forum C Programming
    Replies: 19
    Last Post: 10-27-2005, 02:01 PM
  4. Realloc problems with sturcture array inside structure
    By daveyand in forum C Programming
    Replies: 2
    Last Post: 03-29-2004, 06:48 AM
  5. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 04:40 PM