Ryn*_*yno 2 c size null pointers realloc
我得到这个错误,在线搜索没有解决它,这是我的代码^^:
void addSoggetto(char* s)
{
soggetti_length++;
if(realloc(soggetti, soggetti_length*sizeof(int))==NULL)
{
printf("Realloc Failed");
return;
}
Run Code Online (Sandbox Code Playgroud)
基本上我有一个指针数组(soggetti)和它的长度(soggetti_length).每次运行此函数时,我都会重新分配大小以便为另一个指针设置位置.问题他,正是第五次调用该函数,我得到:
realloc(): invalid next size
Run Code Online (Sandbox Code Playgroud)
你知道我该怎么办?我想我可以排除我realloc的内存不是enaugh,我依旧增加它并且没有任何变化.哦,我用gdb调试它,该函数在返回之前崩溃,所以我甚至得不到像NULL返回的东西
阅读联机帮助页realloc().realloc()返回指向新分配的指针,它不会更改您作为参数传递的旧指针.(它不能,因为C使用pass by value,而不是通过引用传递).所以
if(realloc(soggetti, soggetti_length*sizeof(int))==NULL)
Run Code Online (Sandbox Code Playgroud)
是一个内存泄漏(和错误).你需要这样的东西:
if(sogetti = realloc(soggetti, soggetti_length*sizeof(int)))
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,分配失败也会泄漏内存.所以,为了安全起见,你可以这样做:
void *newpointer;
if(newpointer = realloc(soggetti, soggetti_length*sizeof(int)))
{
sogetti = newpointer;
}
else
{
//handle out-of-memory
}
Run Code Online (Sandbox Code Playgroud)
使用其余代码,我们可以看到另一个问题:
Soggetto* new = malloc(sizeof(Soggetto));
...
soggetti[soggetti_length-1]= new;
Run Code Online (Sandbox Code Playgroud)
你已经分配了一个int值的内存(sizeof(int))sogetto_length,但你存储的是64位Sogetto *.这会通过覆盖内存中的元数据来破坏堆(因此invalid next size,size堆数据结构的一部分被覆盖).
写
void *newpointer;
if(newpointer = realloc(soggetti, soggetti_length*sizeof(Sogetto *))) //here!
{
sogetti = newpointer;
}
else
{
//handle out-of-memory
}
Run Code Online (Sandbox Code Playgroud)
要正确处理这个问题.为了找到这样的错误,我建议valgrind,address sanitizer.