C警告:函数返回局部变量的地址 [英] C Warning: Function returns address of local variable
问题描述
下面的函数将包含应用程序的调用路径,并取代了最后一位,直到它击中的argv [0]参数的/与新的应用程序,我想产卵,它位于同一文件夹的名称
BTW:我声明了一个全球性的argv变量所以函数可以访问它,因为我不想在传递每个函数调用的信息
当我编译我的code,一切似乎工作,但我得到了上述警告。
我知道我只要函数返回将会被销毁声明变量和。
作为一个初学者C程序员我想知道解决这个问题的最优雅/最简单的方法是什么呢?
我应该通过一个函数指针或malloc的一些内存?
的char * returnFullPath()
{
炭pathToApp [strlen的(argv的[0])+ 1〕;
的strcpy(pathToApp,argv的[0]);
INT PATH_LENGTH = strlen的(的argv [0]); 而(pathToApp [PATH_LENGTH]!='/')
{
路径长度 - ;
} 如果(PATH_LENGTH→2)
pathToApp [PATH_LENGTH + 1] ='\\ 0';
其他
pathToApp [0] ='\\ 0'; // GETCWD + pathtoapp + 1的长度长度为零加6bidbot
炭bidbotPath [strlen的(GETCWD(NULL,0))+的strlen(pathToApp)+ 1 + 6]; 的sprintf(bidbotPath,%S /%sbidbot,GETCWD(NULL,0),pathToApp); 返回bidbotPath;
}
一些其他的答案建议你的malloc的东西并将其返回。这是在同样的意义不好的做法,因为在C ++中,当你在一个函数调用者新的东西是应该将其删除(谁拥有所有权?)
有一个原因,许多C API已格式:
功能(BUF,长度);
意味着调用者会提供缓冲区,并有多长。这是调用者的责任分配和取消分配该缓冲区和你的函数应该使用它,并检查你就不会溢出的长度。
不要malloc和回报。这只是自找麻烦。
The function below takes the argv[0] argument that contains the calling path of the application and replaces the last bit until it hits a "/" with the name of the new app I want to spawn that sits in the same folder.
BTW: I'm declaring a global argv variable so the function can have access to it because I did not want to pass the info in every function call.
When I compile my code, all seems to work, but I get the above warning.
I know that I'm declaring the variable and that as soon as the function returns it will be destroyed.
Being a beginner C programmer I wanted to know what the most elegant/easiest way of solving this problem would be?
Should I pass a pointer to the function or malloc some memory?
char *returnFullPath()
{
char pathToApp[strlen(argv[0])+1];
strcpy(pathToApp, argv[0]);
int path_length = strlen(argv[0]);
while (pathToApp[path_length] != '/')
{
path_length--;
}
if (path_length > 2)
pathToApp[path_length+1] = '\0';
else
pathToApp[0] = '\0';
// length of getcwd + length of pathtoapp + 1 for zero plus 6 for "bidbot"
char bidbotPath[strlen(getcwd(NULL,0)) + strlen(pathToApp) + 1 + 6];
sprintf(bidbotPath, "%s/%sbidbot", getcwd(NULL,0), pathToApp);
return bidbotPath;
}
Some other answers suggest that you malloc something and return it. This is bad practice in the same sense as in C++, when you new something in a function and the caller is supposed to delete it (who has ownership?)
There is a reason that many C APIs have the format of:
function(buf, length);
Meaning that the CALLER supplies the buffer and how long it is. IT is the caller's responsibility to allocate and de-allocate this buffer and your function should use it, and check that you're not going to overflow the length.
Do not malloc and return. It's just asking for trouble.
这篇关于C警告:函数返回局部变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!