我对 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;
}
为什么 realloc()
当我使用 sizeof(int) * cpt
时导致错误而不是 sizeof(amis) + sizeof(int)
?
free(amis)
在这种情况下也不起作用。
最佳答案
您遇到的最大问题是您似乎混淆了指针和数组。如果您使用数组,则:
int foo[10];
printf("%zu\n", sizeof foo/ sizeof *foo);//sizeof foo/sizeof(int)
会给你数组的长度,但是指针不是数组。 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...
因此 sizeof amis
将始终是相同的值:内存地址的大小(32 位为 4,64 位为 8)。为了解决这个问题,您将不得不自己跟踪分配 block 的大小:
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);
等等。
您应该做的其他事情是:初始化您的变量:
int *amis = NULL,
saisie = 0;
修复scanf
的格式,检查saisie
的值是否为负值除了-1...
最后但并非最不重要:exit(0);
表示您正在终止执行,退出状态为 0。0 表示进程无错终止,而 malloc
或 realloc
失败 是 一个错误,使用 stdlib
宏 exit( EXIT_FAILURE );
,或以非零值退出。
在 main 函数返回之前在指针上调用 free
是一件毫无意义的事情,但是调用 free
是一个养成的好习惯,所以你可以把它留在那里。
但是,请尝试习惯将 NULL
分配给您释放的任何指针:
free(amis);
amis = NULL;
关于c - 为什么我的代码中的 realloc() 和 free() 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868021/