c - 为结构数组中的结构成员分配内存后写入无效
问题描述
我需要将一个结构数组传递给一个函数,我的理解是我必须为整个结构数组以及数组内每个结构中的每个单独的结构成员分配内存。
我这样做的方式导致来自 valgrind 的无效写入错误(在函数 read_file 内的第二行引起)。怎么了?
typedef struct test
{
char *string1;
int num1;
int num2;
char *string2;
} Test;
static void read_file(Test *test)
{
test = (Test *)calloc(16, sizeof(test));
test[0].string1 = (char *)calloc(strlen("hello") + 1, sizeof(char));
}
int main(void)
{
int i = 0;
Test test[16];
for (i = 0; i < 16; i++)
{
memset(&test[i], 0, sizeof(test[i]));
test[i] = (Test) { "", 0, 0, "" };
}
read_file(test);
return 0;
}
PS:我知道我必须释放分配的内存,但首先我想让上面的代码工作。
解决方案
中的test
数组main
已经为其分配了内存。
然后将其传递给read_file
函数,因此您无需再次为其分配内存。删除这个:
test = (Test *)calloc(16, sizeof(test));
顺便说一句,您可能打算sizeof(Test)
(或替代地sizeof(*test)
)在那里。sizeof(test)
与 相同sizeof(Test*)
,几乎可以肯定小于sizeof(Test)
。
推荐阅读
- python - Selenium 抓取数据但抛出错误 TimeoutException
- javascript - 如何一次按日期和时间对对象数组进行排序
- mysql - 这是一个有效的 sql 语句吗?或者有更好的选择吗?
- c# - 为什么 EF Core 在后续查询中过滤错误?
- abap - 错误“数据库表和工作区......不是 Unicode 可转换”
- javascript - JSON 对象未从 XMLHttpRequest 发送以表达
- wordpress - Wordpress Soeldad 元信息隐藏
- shopware - NetzpSearchAdvanced6 是否支持多种销售渠道?
- jquery - 如何突出显示引导程序 3 中的活动链接?
- javascript - 将旋转的子 div 粘贴到父级的底部