gpt4 book ai didi

条件跳转或移动取决于未初始化的值和在 retval 上分配的指针

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:04 24 4
gpt4 key购买 nike

我得到这个 Valgrind 输出(这是我得到的唯一错误):

==20627== Conditional jump or move depends on uninitialised value(s)
==20627== at 0x804913A: main (main.c:223)

我的 main.c 大致如下所示:

//other code

char **sets;

//other code

//char** get_char_sets(FILE *source);
sets = get_char_sets(config_file); // I malloc the sets in here

//other code

int i = 0;
while(sets[i]){ // line 223
free(sets[i]);
i++;
}
free(sets);

//other code

get_char_sets 看起来像这样:

char** get_char_sets(FILE *source){

char **sets = malloc((n + 1) * sizeof(char*));

for(int i=0;i<=n;i++){
sets[i] = malloc(1 * sizeof(char));
}

//rest of function

return sets;
}

我知道 valgrind 说我正在使用一个未初始化的变量,我唯一可能看到的是 sets,但它得到了 malloc() get_char_sets() 然后用返回的指针赋值。

如何消除 valgrind 错误以更正我的代码?

最佳答案

i的取值没有限制,最终会导致越界:

while(sets[i]){

更改为(类似于):

int i = 0;
while(i <= n && sets[i]){ /* Ensure check i <= n before accessing sets */
free(sets[i]);
i++;
}
free(sets);

您还可以将 NULL 标记值添加到 sets 中,while 就可以了。

关于条件跳转或移动取决于未初始化的值和在 retval 上分配的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10300541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com