Here is a snippet of code that displays the problem I am having with realloc in a much larger program:
Code:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *int_array,counter, size,size1;
printf("How many members in the array do you want: ");
scanf("%d",&size);
// Allocates memory for the int_array
int_array=(int *)malloc(size*sizeof(int));
// Places a value in each index position
for(counter=0;counter<size;counter++)
int_array[counter]=10+counter;
printf("\nThe array has the following elements: \n");
// Prints values
for(counter=0;counter<size;counter++)
printf("%d\n",int_array[counter]);
printf("What would you like the new size to be: ");
scanf("%d",&size1);
// Should reallocate the array to size size1
int_array=realloc(int_array,size);
printf("\nThe array now has the following elements: \n");
// Runs until counter is equal to the original size...When I increase the size using
// realloc the values up until the original size should remain unchanged, but
// they are not when i print them out
for(counter=0;counter<size;counter++)
printf("%d\n",int_array[counter]);
system("PAUSE");
return 0;
}
HERE IS THE OUTPUT I GET: (I ran this on two machines and it came up with the same numbers)
Like I said, I am running into this problem in a much larger project, if anyone can help it would be greatly appreciated.
How many members in the array do you want: 10
The array has the following elements:
10
11
12
13
14
15
16
17
18
19
What would you like the new size to be: 11
10
11
12
13
196697
15
3998784
3998784
18
393302