Thread: malloc() and realloc(): I think I'm doing it wrong.

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    7

    malloc() and realloc(): I think I'm doing it wrong.

    So, I had what I thought was a piece of functional code. Apparently not. I've actually got two problems here, so I'll list them seperately. The code I've got here is probably poorly optimised/wrong/etc. As a novice in C, I'd prefer something that is functional and pretty clear in what it's doing over some sleek, shiny but confusing way of doing things.

    Problem 1
    In this, I have a 2-dimensional array that I need to resize a few times, depending on user input. Thus, I have:
    Code:
    int a;
    int **specialarray;
    specialarray = malloc(12*sizeof(int*));
    for (a = 0; a < 12; a++)
    {
     specialarray[a] = malloc(1*sizeof(int));
    }
    So, this just sets up a 12 x 1 array. (Come to think of it, I need to add in some if-it's-a-NULL-no-space-left thing in there, but that's something else.) Next up, I want to resize that array, which will happen a few times, so I've got:
    Code:
    <specialcount is a static incremented once every time the function handling this is called>
    for (a = 0; a < 12; a++)
    {
     if((specialarray[a] = realloc(specialarray[a], specialcount*sizeof(int))) == NULL)
     {
      printf("\n\nOut of memory! Could not create special.\n");
      end_program();  //Custom function that free()s everything before quitting.
     }
    //printf("%d ", (specialcount*sizeof(int)));
    }
    /*Some data put into specialarray[<1-12>][specialcount]*/
    So this should just resize my array from being 12x1 to 12x2, 12x3 etc.
    But for some probably obvious reason, my code is screwing up here. It seems happy to call this bit of code exactly 3 times. The commented out printf statement returns 4, then 8, then 12, those first 3 times - as expected. But the fourth time, it freezes up during the if statement before it hits the printf statement, and I have no idea why.

    Problem 2
    This might be related to the previous one, as it's affecting part of the same data (although it shouldn't be...)
    In this one, I've previously called that bit of code 3 times - where it seems to work fine. But then later on, something strange happens, in which one part of specialarray is modified for some reason. Some debug printf statements either side of this next bit of code show that it is changing specialarray[11][3] from 0 to 35... (0 being what I set it as earlier on.)
    Code:
    /*Here it is 0*/
    nbytes = 20;
    if ((inputstring2 = (char *) malloc (nbytes+1)) == NULL)
    {
     printf("\nNot enough memory!\n");
     end_program();
    }
    /*Here it is 35*/
    I'm completely at a loss for this one, it shouldn't even touch specialarray at all, these two bits do completely different things. And yet it does. I'm not sure if I've got the right information here as for why it's affecting there specifically, but some guidance on why it's affecting anything at all would still be helpful.

    *sigh* And there was me thinking I was getting the hang on malloc() and realloc().

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    As for 1, I don't see anything that will definitely cause a crash, but you have the potential to generate memory leaks and invalid pointers, which could cause your problems. When using realloc, you always want a temp pointer, incase the realloc fails, so you don't lose a handle to the original memory:
    Code:
    int *original_array = malloc(10 * sizeof(int));  // allocate 10 ints
    int *temp = realloc(original_array, 20 * sizeof(int));  // realloc 20 ints
    if (temp == NULL) {
        perror("realloc");
        // probably exit with a failure
    }
    original_array = temp;  // original array now contains the new, larger array
    As for problem 2, again, there's nothing definitely wrong in the code you posted. It's quite likely you have some sort of pointer bug or array overflow error. It sounds like something is altering memory it doesn't own. You should also avoid casting malloc. Read this FAQ article.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Woobly View Post
    So this should just resize my array from being 12x1 to 12x2, 12x3 etc.
    But for some probably obvious reason, my code is screwing up here. It seems happy to call this bit of code exactly 3 times. The commented out printf statement returns 4, then 8, then 12, those first 3 times - as expected. But the fourth time, it freezes up during the if statement before it hits the printf statement, and I have no idea why.
    Just re-read this, and noticed the "freezing" comment. Do you know if your realloc is succeeding/failing? Maybe the problem is in end_program, and you don't correctly free everything. Also, you should learn to use a debugger for problems like this. Gobs of print statements get messy and don't always work as you expect. As a matter of fact, you don't want to send debug output to stdout, since it's buffered and doesn't always make it to the screen right away, misinforming you of where you were when it crashed. You should use fprintf(stderr, "Same debug message as before").


    Even better would be learn to use a debugger. When your program "freezes", you can pause execution and see exactly where you are in the code and why it isn't completing that section (e.g. infinite loop due to incorrect loop termination condition). You can also inspect the values of variables while stepping thought your program line-by-line and get a trace of exactly where it was if/when it crashed. We have some debugging tutorials here, and Google has tons more.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Use of malloc and realloc
    By mrbains in forum C Programming
    Replies: 5
    Last Post: 11-11-2010, 02:53 AM
  2. malloc and realloc
    By jayfriend in forum C Programming
    Replies: 4
    Last Post: 01-05-2007, 02:25 PM
  3. malloc, realloc
    By figo2476 in forum C Programming
    Replies: 3
    Last Post: 04-28-2006, 10:11 PM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc and realloc
    By C-Struggler in forum C Programming
    Replies: 2
    Last Post: 03-11-2003, 11:31 AM