简体   繁体   English

Strcat初始化值

[英]Strcat initialized value

I have code like this: 我有这样的代码:

char *all_arguments = (char *) malloc(sizeof(char)*argc);

for(int i=1; i<argc; i++) {
    strcat(all_arguments, argv[i]);
}

valgrind output: valgrind输出:

==20425== Conditional jump or move depends on uninitialised value(s)
==20425==    at 0x4C30C0A: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==20425==    by 0x40065B: main (main.c:15)

What is wrong? 怎么了? I know that I should initialize all_arguments, but when I do "all_arguments = NULL;" 我知道我应该初始化all_arguments,但是当我执行“ all_arguments = NULL;”时, I got a segmentation fault. 我遇到了细分错误。

Two problems: 两个问题:

1) You don't allocate enough memory for all_arguments . 1)您没有为all_arguments分配足够的内存。 Even if each argument is only a single character, you still don't have space for the string terminator. 即使每个参数只是一个字符,您仍然没有足够的空间来容纳字符串终止符。 And presumably, at least some of the arguments are larger. 大概至少有一些论点更大。

2) Since all_arguments is not a string when it's first allocated, you can't pass it to strcat . 2)由于all_arguments首次分配时不是字符串,因此无法将其传递给strcat The arguments to strcat must both be strings. 到的参数strcat 必须是字符串。 The first time you call strcat , all_arguments is not valid string. 第一次调用strcatall_arguments无效的字符串。

argc holds number of parameters received to function main I assume. argc拥有我假设的函数main接收的参数数量。

So, before you copy new memory, simply realloc (extend) your memory for next entry. 因此,在复制新内存之前,只需重新分配(扩展)内存以供下次输入。

char * all_parameters = malloc(1);

*all_parameters = 0; //Create valid string
for (int i = 1; i < argc; i++) {
    //Extend to new size
    all_parameters = realloc(all_parameters, strlen(all_parameters) + 1 + strlen(argv[i]);
    //Copy together
    strcat(all_parameters, argv[i]);
}

Another option is to sum all lengths first and then use malloc only once. 另一个选择是先对所有长度求和,然后仅使用malloc一次。

int total_sum=0; // remember to initialize variable 
for (int i = 1; i < argc; i++) {
    total_sum += strlen(argv[i]);
}

char * all_parameters = malloc(total_sum + 1);
*all_parameters = 0;
for (int i = 1; i < argc; i++) {
    strcat(all_parameters, argv[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM