c++ - 从函数返回 'local' char* 与从函数返回 'local' int* 之间的区别

标签 c++ c string heap-memory stack-memory

Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?

这是一个简单的代码,其中 3 个不同的函数 [ localStrPtr, localIntPtr, localCharPtr] 返回指向其局部变量 [string, integer, char] 的指针各自的职能。

代码:

#include <stdio.h>

char*  localStrPtr (char*);
int*   localIntPtr (int, int);
char*  localCharPtr (char);

main()
{
    int *pInt;
    char *pChar;

    printf( "localStrPtr = %s\n", localStrPtr("abcd") );

    pInt = (int*) localIntPtr(3, 5);
    printf( "localIntPtr = %d\n", *pInt );

    pChar = (char*) localCharPtr('y');
    printf( "localCharPtr = %c\n", *pChar );
}

char* localStrPtr(char* argu)
{
    char str[20];
    // char* str = (char*) malloc (20);

    strcpy (str, argu);
    return str;
}

int* localIntPtr (int argu1, int argu2)
{
    int local;
    local = argu1 + argu2;
    return (&local);
}

char* localCharPtr (char argu)
{
    char local;
    local = argu;
    return (&local);
}

编译日志:

stringManip.c: In function `localStrPtr':
stringManip.c:27: warning: function returns address of local variable
stringManip.c: In function `localIntPtr':
stringManip.c:34: warning: function returns address of local variable
stringManip.c: In function `localCharPtr':
stringManip.c:41: warning: function returns address of local variable

运行日志:

localStrPtr =
localIntPtr = 8
localCharPtr = y

正如您在日志文件中看到的,localStrPtr 返回“一些垃圾”,而 localIntPtr 和 localCharPtr 返回“预期”值。

但是,在函数 localStrPtr 中,如果我将 [ "char str[20]"-to-> "char* str = (char* ) malloc(20)"], localStrPtr 正确返回字符串“abcd”。这是进行上述更改后的运行日志。

新的运行日志:

localStrPtr = abcd
localIntPtr = 8
localCharPtr = y

问题:

  1. 在函数 localIntPtr 和 localCharPtr 中,返回的局部变量地址内容有效,但对于函数 localStrPtr,使用 malloc 时“仅”返回正确的值,但对于本地 char 则不会返回正确的值字符串[20]。为什么它不能与 str[20] 一起使用?

  2. 为什么我们在编译日志中看到所有 3 个函数的以下行?

    • stringManip.c:27:警告:函数返回局部变量的地址
    • stringManip.c:34:警告:函数返回局部变量的地址
    • stringManip.c:41:警告:函数返回局部变量的地址

最佳答案

在所有 3 种情况下,行为均未定义。这个“未定义”包括它可能起作用的可能性。或者看起来它正在工作。有时。

您将返回一个指向局部变量的指针,该变量在堆栈上分配。当该变量超出范围时(即函数返回时),该内存不再保留给该变量。内容是否会被更改以及何时发生更改都取决于运气。正如您的情况一样,您在几个案例中很幸运,但在其他案例中却没有。在不同的日子,编译器可能会在内部做出一些不同的选择,并且其行为也会有所不同。或者也许(可能)当您下次打喷嚏时数据会被覆盖。

不要这样做。

关于c++ - 从函数返回 'local' char* 与从函数返回 'local' int* 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14226080/

相关文章:

c - 快捷方式评估而不是做 if(condition) 表达式;

arrays - 匹配 shell 中的单词后分割字符串

java在2个小数位后剪切字符串?

c++ - 如何使用c++在sqlite中插入wchar?

c++ - boost::optional<> 如何处理局部变量?

c++ - 安装 wxwidgets 2 时出现问题

android - android内核中的c指针类型比较

c++ - VERIFY(...) 是 C++ 编码的好习惯吗?

c - 将 C 字符数组读入 double

Javascript:切片和子字符串未按预期工作