gpt4 book ai didi

c - 函数 join() 中 char 和 char* 出现问题

转载 作者:行者123 更新时间:2023-11-30 19:38:45 25 4
gpt4 key购买 nike

我正在使用以下签名在 C 中实现一个函数:

char *join(char **strv, char sep); 

该函数接收一个字符串数组,并返回一个字符串,其中包含数组中的所有子字符串,并用字符“sep”分隔。

我的代码可以工作,但 Valgrind 提示:

==2526== Command: ./strutil

==2526==

==2526== Conditional jump or move depends on uninitialised value(s)

==2526== at 0x4C2EC78: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==2526== by 0x400CDE: strcat (string3.h:148)

==2526== by 0x400CDE: join (strutil.c:90)

==2526== by 0x4006EE: main (strutil.c:117)

==2526== Uninitialised value was created by a stack allocation

==2526== at 0x400C30: join (strutil.c:72)

==2526==

==2526== Conditional jump or move depends on uninitialised value(s)

==2526== at 0x4C2EC78: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==2526== by 0x400CDE: strcat (string3.h:148)

==2526== by 0x400CDE: join (strutil.c:90)

==2526== by 0x400722: main (strutil.c:121)

==2526== Uninitialised value was created by a stack allocation

==2526== at 0x400C30: join (strutil.c:72)

==2526==

==2526==

==2526== HEAP SUMMARY:

==2526== in use at exit: 0 bytes in 0 blocks

==2526== total heap usage: 15 allocs, 15 frees, 474 bytes allocated

==2526==

==2526== All heap blocks were freed -- no leaks are possible

==2526==

==2526== For counts of detected and suppressed errors, rerun with: -v

==2526== ERROR SUMMARY: 3 errors from 2 contexts (suppressed: 0 from 0)

这是我调用该函数的方式:

char *result = join(strv, ';');

我发现我可以通过使用双引号来解决问题,并将函数签名更改为 char *join(char **strv, char* sep);但我不应该更改函数签名。

这是给我带来麻烦的行:

strcat(string, &sep); 

“string”是返回值。

有没有办法可以在不更改函数签名的情况下解决问题?

提前致谢。

最佳答案

不,鉴于该签名,此问题无法解决,因为您无法在不知道数组大小的情况下迭代 C 中的数组。

如果您更改了签名以包含某种尺寸,那么您可以采用 David Rankin 在评论中给出的方法。

关于c - 函数 join() 中 char 和 char* 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510559/

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