简体   繁体   中英

Best way of using malloc and realloc

I'm pritty new to using malloc and realloc and I have a few questions.

Question 1.

The game I am making allows you to create your own spaceschip, knowing this I was wondering is it better to realloc twice the ammount of the current memory which is the standard. Or do something along the lines of reallocing 100 extra spaces for the needed vertexes? I my self think the seccond option would be better but maybe there is something I'm not aware of.

Question 2

If I have a malloced array of squares[20] [4] How do I realloc it to a size of squares[100][4]? Do I realloc the 1st array to 100 and then malloc 20-99 with 4 new spots?

Question 3

Right now something strange happens when I realloc my data. If I put down a break point everything goes fine but if I let the code work all at once it crashes. So I'm guessing there is a memory leak. Right now this is my realloc code.

unsigned char *temp =( unsigned char* ) realloc(realSpaceship, gridSize*sizeof( unsigned char ));
if(temp != NULL)
{
    realSpaceship = temp;
    //free(temp); Line is now deleted at the advice of the helpfull people here.
}
else
{
    //error
    printf("realloc error\n");
    free(realSpaceship);
}

I figgured freeing temp was a good idea but it just couses the code to crash at a different location.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I just realised the problem is not with the realloc but somewhere else.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

A litle extra information. I'm using c++ And I'm also using glm

Honestly, avoid using realloc multiple times. malloc once and stick with that until you run into an extreme case, then realloc (but even then, avoid it!)

The main reason for this is debugging and testing. If the program fails at realloc , it can be for multiple reasons... and most of it comes from the OS. (ie not enough memory, trying to use memory just freed, etc.) Those are tough bugs to reproduce and debug.

Do a little math, calculate the max you will need for your use case and malloc that. Move onto coding other stuff. Debugging realloc errors are no fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM