One of my classmates sent me a code and asked what was wrong with it. It was something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *d_array, number, divisor_count, i, size = 1;
char answer;
d_array = (int*) malloc(size * sizeof(int));
do
{
printf("\nEnter a number: ");
scanf("%d", &number);
divisor_count = 0;
for(i = 2; i < number; i++)
if (number % i == 0) divisor_count++;
if(divisor_count == 0)
{
realloc(d_array,(size + 1) * sizeof(int));
d_array[size - 1] = number;
size++;
}
printf("\nIs there another number? y/n ");
getchar();
answer = getchar();
} while (answer == 'y');
for(i = 0; i < size - 1; i++)
printf("\n%d", d_array[i]);
return 0;
}
It's supposed to get numbers from the user and keep the ones that are prime and print them in the end. The output on my computer is something like:
Enter a number: 3
Is there another number? y/n y
Enter a number: 5
Is there another number? y/n y
Enter a number: 8
Is there another number? y/n y
Enter a number: 7
Is there another number? y/n y
Enter a number: 2
Is there another number? y/n n
4072680
5
7
2
There were other things in the code but the biggest problem is obviously not assigning the return value of realloc(). But the strange thing is, which is my question, why does this code shows the first prime number wrong and the others correct? The adress of the dynamic array possibly changes but why are the second one and the rest correct and not the first one?
Edit: Ok, the reason why I asked this was to try to understand the behaviour of realloc() in this code, if you have good resources please do share. When reallocating memory (when it is freeing the old one), does realloc() change the content of the old memory location?