realloc problems

This is a discussion on realloc problems within the C++ Programming forums, part of the General Programming Boards category; I use realloc to find a new memory location assign it to a pointer and copy its old data to ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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, 04: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, 05:48 AM
  5. segfault on realloc
    By ziel in forum C Programming
    Replies: 5
    Last Post: 03-16-2003, 03:40 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21