[英]Error : realloc(): invalid pointer
我想在struct MotInfo**
char**
,这是我创建的结构。 但是当我尝试重新realloc
时出现错误:
int x;
MotInfo** hashtable = malloc(TAILLE*sizeof(struct MotInfo*));
for(x=0; x<TAILLE;x++)
{
hashtable[x] = NULL;
}
struct MotInfo* mot_info;
int i;
hashtable[5] = malloc(sizeof(struct MotInfo*));
mot_info = malloc(sizeof(struct MotInfo*));
mot_info->mot = "manger";
mot_info->urls = malloc(2*sizeof(char*));
mot_info->occurrences = malloc(2*sizeof(int));
mot_info->taille = 2;
for(i = 0;i<2;i++)
{
mot_info->urls[i] = "http://stackoverflow.com/questions";
mot_info->occurrences[i] = 3;
}
printf("OK\n");
hashtable[5] = mot_info;
hashtable[5]->urls = realloc(hashtable[5]->urls, sizeof(char*)*2);
我在最后一行中定位了我的错误,但是我遇到了这个错误:
realloc(): invalid pointer:
struct MotInfo* mot_info;
mot_info = malloc(sizeof(struct MotInfo*));
mot_info
是指向struct MotInfo
的指针,但是您分配的空间仅足以容纳一个指针,而不是该结构(由于它至少具有四个成员,因此可能会更大)。 当您超额分配时,您可能会m脚malloc的簿记。
hashtable[5] = malloc(sizeof(struct MotInfo*)); // (a)
mot_info = malloc(sizeof(struct MotInfo*));
hashtable[5] = mot_info; // (b)
(b)的分配丢失了指向(a)分配的块的指针。
mot_info->urls = malloc(2*sizeof(char*));
hashtable[5] = mot_info;
hashtable[5]->urls = realloc(hashtable[5]->urls, sizeof(char*)*2);
我也不明白这一点,你不realloc
荷兰国际集团以同样的大小?
即使没有,您也不应立即将realloc
的返回值分配给同一指针:如果realloc
失败,它将丢失指向内存块的指针。
您做了hashtable[5] = malloc(sizeof(struct MotInfo*))
但是hashtable[5]
本身是指向struct MotInfo
的指针,因此您可能会做hashtable[5] = malloc(sizeof(struct MotInfo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.