C返回char []警告“返回本地变量的地址". [英] C Returning char[] Warning "returns address of local variable"

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

问题描述

这是家庭作业的一部分.

This is a portion of a homework assignment.

我试图在我的方法getLine中读取并返回文件的一行.

I am trying to read and return a single line of a file in my method getLine.

char *getLine(FILE *input) {
    char line[30];
    if(fgets(line, sizeof(line), input)!=NULL)
    {
        return line;
    }else{
        return NULL;
    }
}

根据我所教的有关指针的知识,这似乎行得通,但是我无法删除警告消息warning: function returns address of local variable [enabled by default].此警告指的是return line;行.我的作业要求编译时没有任何警告或错误.我看不到我在做什么错.

This would seem to work from what I have been taught regarding pointers, however I am unable to remove the warning message warning: function returns address of local variable [enabled by default]. This warning is referring to the line return line;. My assignment requires that I have no warnings or errors when I compile. I don't see what I am doing wrong.

我发现的大多数帮助都建议为文本行分配空间,但是即使我在另一堂课中做了一些工作,我们也没有在课堂上讨论过.这真的是最好的方法吗?如果是这样,我可以在程序中的任何地方免费使用吗?

Most of the help I found suggested malloc-ing space for the line of text, but we haven't covered that in class yet even though I have done some in another class. Is that really the best way to do this? If so, would I be able to free anywhere in the program?

推荐答案

char line[30];是具有自动存储持续时间的数组.一旦执行超出函数范围,就将其驻留的内存释放,因此指向您返回的该内存的指针将变为无效(悬空指针).

char line[30]; is an array with automatic storage duration. Memory where it resides is deallocated once the execution goes out of the scope of your function, thus pointer to this memory that you return becomes invalid (dangling pointer).

试图访问已被释放的内存,将导致不确定的行为.

Trying to access memory, that has already been deallocated, results in undefined behaviour.

您可以动态分配数组,并让调用者显式取消分配数组:

You can allocate your array dynamically and let the caller explicitly deallocate it:

char *getLine() {
    char* line = malloc(30);
    ...
    return line;
}

// somewhere:
char* line = getLine();
...
free(line);

这篇关于C返回char []警告“返回本地变量的地址".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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