我有一个非常简单的程序,它检查用户参数并打印一些东西。这是:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char * foo(char * input){
char *result = NULL;
strcpy(result, "{ ");
if (strcmp(input, "kittycat") == 0){
strcat(result, "JACKPOT!");
}
else{
strcat(result, "Nothing");
}
strcat(result, " }");
return result;
}
int main(int argc, char *argv[]){
printf("%s\n", foo(argv[1]));
printf("%s\n", foo(argv[1]));
printf("%s\n", foo(argv[1]));
return 0;
}
在main()中,如果我只打印一次printf("%s\n", foo(argv[1]));
,程序运行时没有错误。但是,如果我打印三次,如上所示,我得到&#34;分段错误:11&#34;。有任何想法吗?我知道我可以简化foo并避免使用&#34; char * result&#34;,但我想了解我使用&#34; char * result&#34;。< / p>
答案 0 :(得分:2)
const char * foo(char * input) {
char *result;
strcpy(result, "{ "); // 'result' used uninitialized - undefined behavior
result
未初始化。注意编译器警告。
另外,我假设你想在这里检查input
,而不是result
:
if (strcmp(result, "kittycat") == 0) {
此版本返回静态字符串:
const char *foo(char *input) {
if (strcmp(input, "kittycat") == 0)
return "{ JACKPOT! }";
return "{ Nothing }";
}
此版本会返回malloc
d字符串,您需要free
:
#define MAX_FOO_RESULT 20
const char *foo(char *input) {
char *result = malloc(MAX_FOO_RESULT+1);
if (!result) return NULL;
result[0] = '\0';
strncat(result, "{ ", MAX_FOO_RESULT);
if (strcmp(input, "kittycat") == 0)
strncat(result, "JACKPOT!", MAX_FOO_RESULT);
else
strncat(return, "Nothing", MAX_FOO_RESULT);
strncat(result, " }", MAX_FOO_RESULT);
return result;
}
int main(int argc, char *argv[]){
const char* res;
if (argc < 2) return 1;
// memory leak - result of foo is leaked
printf("%s\n", foo(argv[1]));
// fixed leak
res = foo(argv[1]);
if (res) {
printf("%s\n", res);
free(res);
}
return 0;
}