C字符串返回函数返回垃圾 [英] C String Return Function Returns Garbage
问题描述
我无法从函数返回字符串。它在主要方法中打印出垃圾值。我在这个论坛上看到了类似的问题,但该页面上的结果并没有帮助我。我不想将另一个变量传递给函数。我希望能够按原样返回字符串值。我怎么能这样做?
I'm having trouble return a string from a function. It prints out a garbage value in the main method. I saw a similar question on this forum but the results on that page didn't help me. I DO NOT want to pass another variable into the function. I want to be able to return the string value as is. How can I go about doing so?
char *LookupPath(char **argv, char **dir)
{
/* String Name To Be Returned */
char path_name[MAX_PATH_LEN] = {0};
char *result = malloc(sizeof(path_name));
int i;
/* Check To See If File Name Is Already An Absolute Path Name */
if(*argv[0] == '/') {
}
/* Look In Path Directories */
for(i = 0; dir[i] != NULL; i++) {
strncat(path_name, dir[i], sizeof(path_name));
strncat(path_name, "/", sizeof(path_name));
strncat(path_name, argv[0], sizeof(path_name));
result = path_name;
if(access(result, F_OK) == 0) {
printf("result: %s\n", result);
return result;
}
path_name[0] = '\0';
}
/* File Name Not Found In Any Path Variable */
return NULL;
}
您的帮助非常感谢!
推荐答案
result = path_name;
应该是:
should be:
strcpy(result, path_name);
或者更好的办法是摆脱 path_name
和直接使用 result
。
Or better, get rid of path_name
and use result
directly.
请注意,您应该记住 result
当它没有被使用时,当它返回时,将它释放到调用它的函数中。既然你在失败时返回 NULL
,在这种情况下,直接释放它,或者它是内存泄漏。
Note that you should remember to free result
when it's not used, when returning it, free it in the function that calls it. Since you return NULL
in failure, in that case, free it directly, or it's a memory leak.
您正在使用 strncat
错误,请阅读手册。
And you are using strncat
wrong, read the manual.
这篇关于C字符串返回函数返回垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!