我正在从我的 C 代码中调用一个 bash 脚本,假设生成一个文本文件并返回它的链接。这就是为什么我使用 popen 而不是 system 的原因,因为我需要它的输出流 所以我解析链接并想将它存储在 C 中的字符串中。我就是这样做的:
#define LINK_KEY "FILE LINK:"
-------------------
char *the_link;
int is_set = 0;
FILE *call_script;
call_script = popen("/location/of/script/script.sh", "r");
if (call_script == NULL) {
fprintf(stderr, "Could not script. Aborting...\n");
exit(EXIT_FAILURE);
}
char *line;
int line_len = 128;
line = malloc(sizeof(char)*line_len);
while (fgets(line, line_len, call_script) != NULL) {
int line_len = strlen(line);
if (line[line_len-1] == '\n') {
if (strstr(line, LINK_KEY)) {
int j;
for (j = 0; j < strlen(line); j++) {
if (line[j] == ':') {
is_set = 1;
break;
}
}
if (is_set) {
int link_len = line_len - j - 1;
if (link_len <= 0) {
fprintf(stderr, "Error in finding file. Aborting...\n");
exit(EXIT_FAILURE);
}
the_link = malloc(sizeof(char) * (link_len +1)); // <=== here is where valgrind complains
strncpy(the_link, &line[j + 1], link_len - 1);
the_link[link_len] = '\0';
}
}
} else {
line_len*=2;
line = realloc(line, sizeof(char)*line_len;
}
}
if (!is_set) //.... throw error and abort
我不知道为什么 Valgrind 提示变量没有初始化:
==7196== Uninitialised value was created by a heap allocation
==7196== at 0x4A0887C: malloc (vg_replace_malloc.c:270)
==7196== by 0x4018A7: main (jumping_al.c:172)
最佳答案
这段代码:
the_link = malloc(sizeof(char) * (link_len +1)); // <=== here is where valgrind complains
strncpy(the_link, &line[j + 1], link_len - 1);
the_link[link_len] = '\0';
您创建一个大小为 link_len + 1
的缓冲区,然后将 link_len - 1
个字符复制到其中(写入 the_link[0]
到 the_link[line_len-2]
,然后将 NULL
终止符写入数组的最后一个字节。这不会写入到 the_link[link_len-1]
。要么修复 strncpy
调用,要么在该位置写入一些其他已知数据。
关于c - 解析 C 脚本的输出,valgrind 提示未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27523740/