区别 - 从函数返回'local'char *与从函数返回'local'int *

时间:2013-01-08 23:49:53

标签: c++ c string stack heap

  

可能重复:
  Can a local variable’s memory be accessed outside its scope?

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

CODE:

#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);
}

COMPILE LOG:

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返回“some garbage”,而localIntPtr和localCharPtr返回“expected”值。

但是,在函数 localStrPtr 中,如果我改变了[“ char str [20] ” - to-&gt; “ char * str =(char *)malloc(20)”],localStrPtr正确返回字符串“abcd”。一旦进行了上述更改,这是RUN LOG。

NEW RUN LOG:

localStrPtr = abcd
localIntPtr = 8
localCharPtr = y

问题:

  1. 在函数localIntPtr和localCharPtr中,返回的局部变量的内容解决了WORKED,但是对于函数localStrPtr,使用malloc返回正确的值“only”,但是不会使用local char STR [20]。为什么它不适用于str [20]?

  2. 为什么我们在COMPILE LOG中看到所有3个函数的下面几行?

    • stringManip.c:27:warning:function返回局部变量的地址
    • stringManip.c:34:warning:function返回局部变量的地址
    • stringManip.c:41:warning:function返回局部变量的地址

1 个答案:

答案 0 :(得分:2)

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

您将返回一个指向局部变量的指针,该局部变量在堆栈上分配。当该变量超出范围时,该变量将不再保留,该变量将在函数返回时进行。内容是否被改变,以及何时发生,都归结为运气。正如你的情况一样,你很幸运有几个案例,但不是另一个案例。在另一天,编译器可能在内部做出了一些不同的选择,并且它的行为有所不同。或者(可能)下次打喷嚏时数据会被覆盖。

不要这样做。

相关问题