SuperSonic wrote:I have three questions. First, could you please explain exactly what free() does? I kinda get the basic concept but I would rather know all of it^^.
free frees up allocated memory. So you know how malloc/calloc allocates memory for the user? What it essentially does is reserve a certain amount of space. Now if you keep reserving more and more space, eventually you'll run out of space to use. So, when you are done with the memory (no need for it anymore) you should free it. If you don't, it's a memory leak, and can cause problems for you. C handles things via pointers/addresses. A char* for instance is a pointer to a char in memory. So, when you allocate a block of memory, you need to have away of pointing to the memory (otherwise you have a memory leak).
- Code: Select all
char* string = malloc(255);
malloc in that case returns the address of a block of memory (size 255). Now free takes an address and frees the memory it points to. So if you used free(string) it would free the memory that string points to. That means that string now points to memory it shouldn't, so you should set it to point to NULL.
- Code: Select all
free(string);
string=NULL;
SuperSonic wrote:Second, how would I use realloc() to change the size of a 2d array?
I actually posted something you shouldn't do in my previous explanation. To allocate memory for a 2d int array, what you really are doing is allocating an array of int pointers, and then allocating each of those as int arrays.
- Code: Select all
int i;
int a_w = 10;
int a_h = 10;
int ** p;
p = malloc(sizeof(int*)*a_h);
for(i=0;i<a_h;i++)
{
p[i] = malloc(sizeof(int)*a_w); // allocates each sub array individually
}
The second dimension makes allocating/reallocating/freeing the array a lot more complex. To free the above, you must first free the p[i] arrays, and then free the p array. And to reallocate you must reallocate each p[i] array individually as well as reallocate the p array. This can easily get overwhelming. So, really I would recommend allocating a single dimensioned array, and treat it like a two dimensional array. Then whenever you need to reallocate the array, you allocate a new one, copy over the old values into the new one, and then switch them. Still a bit of work, but overall cleaner than dealing with a 2d array.
SuperSonic wrote:And third:
skydereign wrote:But, I think Bee-Ant has mentioned problems with too large arrays, so do watch out for that.
I wrote:Like what problems?
Oh yeah. I searched for it but didn't find the actual problem. Though I believe it had to do with crashing the game (could be wrong).