如何解决在数组为参数的函数内部调用 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;
}
解决方法
函数 tab
的参数 sth
是传递的内容的副本,更改不会影响传递的内容。因此,free(tab);
函数中的 main()
表示 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。