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

查看:30
本文介绍了C Returning 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 return 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.

我找到的大部分帮助都建议为文本行分配 malloc-ing 空间,但我们还没有在课堂上介绍过,即使我在另一堂课上做过一些.这真的是最好的方法吗?如果是这样,我可以在程序的任何地方释放吗?

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 Returning char[] 警告“返回局部变量的地址";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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