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().