C 警告:函数返回局部变量的地址 [英] C Warning: Function returns address of local variable

查看:37
本文介绍了C 警告:函数返回局部变量的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数采用包含应用程序调用路径的 argv[0] 参数并替换最后一位,直到它遇到一个/",其中包含我想要生成的位于同一文件夹中的新应用程序的名称.

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.

顺便说一句:我声明了一个全局 argv 变量,以便函数可以访问它,因为我不想在每个函数调用中传递信息.

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.

作为一名初学 C 程序员,我想知道解决这个问题的最优雅/最简单的方法是什么?

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] = '';
    else
        pathToApp[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;
}

推荐答案

其他一些答案建议您分配一些东西并返回它.这与在 C++ 中的意义相同,这是一种不好的做法,当您在函数中添加新内容而调用者应该删除它时(谁拥有所有权?)

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?)

许多 C API 具有以下格式是有原因的:

There is a reason that many C APIs have the format of:

function(buf, length);

意味着 CALLER 提供缓冲区以及它的长度.分配和取消分配此缓冲区是调用者的责任,您的函数应该使用它,并检查您是否会溢出长度.

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.

不要 malloc 并返回.就是自找麻烦.

Do not malloc and return. It's just asking for trouble.

这篇关于C 警告:函数返回局部变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆