c-在数组是参数的函数内部调用realloc时出现问题



我对realloc有问题。Valgrind返回8 bytes in 1 blocks are definitely lost in loss record 1 of 1。而如果我从main调用函数allocate,它就可以工作了。我不明白有什么区别?如果我把free(tab)放在函数sth中,但我需要在main中使用tab,这是可行的。有人能帮忙找到解决方案吗?

#include <stdio.h>
#include <stdlib.h>
struct x{
int a;
char b;
};

void allocate( struct x **tab,int *size)
{
*size = 1+2*(*size);
*tab= realloc(*tab, (size_t) (*size) * sizeof (**tab));
}

void sth (struct x *tab, int *size)
{
//do something here
allocate(&tab, size);
}
int main(void)
{
int size=0;
struct x *tab=NULL;
sth(tab, &size);
//do sth here with tab
free(tab);
return 0;
}

函数sth的参数tab是传递内容的副本,更改为不会影响传递内容。因此,main()函数中的free(tab);表示free(NULL);。这被定义为什么都不做,也无助于避免内存泄漏。将指针传递到应该修改的内容,以使函数修改传递的内容。

#include <stdio.h>
#include <stdlib.h>
struct x{
int a;
char b;
};

void allocate( struct x **tab,int *size)
{
*size = 1+2*(*size);
*tab= realloc(*tab, (size_t) (*size) * sizeof (**tab));
}

void sth (struct x **tab, int *size) // receive a pointer of struct x*
{
//do something here
// allocate(&(*tab), size);
allocate(tab, size);
}
int main(void)
{
int size=0;
struct x *tab=NULL;
sth(&tab, &size); // pass a pointer to what should be modified
//do sth here with tab
free(tab);
return 0;
}

最新更新