I have some problem with realloc()
:
int main(int argc, char* argv[])
{
int* amis;
int saisie, cpt = 1;
while(saisie != -1) {
printf("Entrer les notes -1 pour quitter :");
scanf("%d", &saisie);
if (cpt == 1) {
amis = malloc(sizeof(int));
if(amis == NULL) {
printf("amis == NULL");
exit(0);
}
}
if(saisie != -1) {
amis = realloc(amis, sizeof (int) + sizeof (amis));
if(amis == NULL) {
printf("amis == NULL cpt= %d", cpt);
exit(0);
}
amis[cpt] = saisie;
printf("size = %d, saisie = %d, tab = %d \n", cpt * sizeof(int), saisie, amis[cpt]);
cpt++;
}
}
printf("%d",1==0);
afficherTab(amis,cpt);
printf("END\n");
free(amis);
return 0;
}
Why does realloc()
cause an error when I use sizeof(int) * cpt
instead of sizeof(amis) + sizeof(int)
?
free(amis)
also doesn't work in that case.
The biggest problem you have is that you seem to confuse a pointer with an array. If you use an array, then:
int foo[10];
printf("%zu\n", sizeof foo/ sizeof *foo);//sizeof foo/sizeof(int)
Will give you the length of the array, but a pointer is not an array. As I've explained here :
A pointer is not an array , so it doesn't need to know what the size of the array is. A pointer can point to a single value, so a pointer can exist without there even being an array. It doesn't even care where the memory it points to is situated (Read only, heap or stack... doesn't matter). A pointer doesn't have a length other than itself. A pointer just is...
So sizeof amis
will always be the same value: the size of a memory address (4 on 32 bit, 8 on 64 bit). To address this, you're going to have to track the size of the allocated block yourself:
size_t amis_size = 0;//use this
scanf(" %d",&saisie);//note the space before %d
amis_size += saisie;
amis = realloc(amis, sizeof *amis * amis_size);
And so on.
Other things you should do is: initialize your variables:
int *amis = NULL,
saisie = 0;
Fix the format of scanf
, and check the value of saisie
for negative values other than -1 ...
Last but not least: exit(0);
means you're terminating the execution, with an exit status of 0. 0 means that the process terminated without error, whereas malloc
or realloc
failing is an error, use the stdlib
macro exit( EXIT_FAILURE );
, or exit with a non-zero value.
Calling free
on a pointer, just before the main function returns is a rather pointless thing to do, but calling free
is a good habit to get into, so you can leave it there either way.
However, try to get used to assigning NULL
to any pointer you free:
free(amis);
amis = NULL;
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.