透明水晶
2021-09-01 12:51
采纳率: 87.5%
浏览 47

C语言 | C语言函数体返回局部变量地址发生段错误

C语言 | C语言函数体返回局部变量地址发生段错误

原始代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *getRandom(void);

int main(int argc, char* argv[])
{
    int *p;
    p = getRandom();

    for(int i = 0; i < 10; i ++)
    {
        printf("*(p + %d) = %d\n", i, *(p + i));
    }

    return 0;
}

int *getRandom(void)
{
    int r[10];

    srand((unsigned)time(NULL));
    for(int i;i < 10; i++)
    {
        r[i] = rand();
        printf("r[%d] = %d\n", i, r[i]);
    }

    return r;
}

编译、运行(发生段错误):

lanfeiy@yelanfei ~/workspace/test
$ make -f c.mk
gcc -o pointerReturn pointerReturn.c -g -Wall
pointerReturn.c: In functiongetRandom’:
pointerReturn.c:38:12: warning: function returns address of local variable [-Wreturn-local-addr]
   38 |     return r;
      |            ^

lanfeiy@yelanfei ~/workspace/test
$ ./pointerReturn.exe
r[1] = 296257045
r[2] = 1976444455
r[3] = 1818576789
r[4] = 755853447
r[5] = 1048925215
r[6] = 2019396098
r[7] = 1255202355
r[8] = 434117987
r[9] = 622347876
Segmentation fault (core dumped)

段错误转储文件:

lanfeiy@yelanfei ~/workspace/test
$ cat pointerReturn.exe.stackdump
Exception: STATUS_ACCESS_VIOLATION at rip=001004010BA
rax=0000000000000000 rbx=000000018023E7A0 rcx=0000000800000010
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
r8 =00000000FFFFC914 r9 =0000000000000000 r10=0000000100000000
r11=0000000100401132 r12=00000000FFFFCC90 r13=00000000FFFFCDF0
r14=0000000000000000 r15=0000000000000000
rbp=00000000FFFFCC40 rsp=00000000FFFFCC10
program=D:\softwareTools\DesTools\Cygwin64\home\lanfeiy\workspace\test\pointerReturn.exe, pid 1149, thread main
cs=0033 ds=002B es=002B fs=0053 gs=002B ss=002B
Stack trace:
Frame        Function    Args
000FFFFCC40  001004010BA (000FFFFCC90, 00180048D30, 00000000000, 00180335BA0)
000FFFFCCE0  00180049EFD (00000000000, 00000000000, 00000000000, 00000000000)
000FFFFFFF0  00180047856 (00000000000, 00000000000, 00000000000, 00000000000)
000FFFFFFF0  00180047904 (00000000000, 00000000000, 00000000000, 00000000000)
End of stack trace

调整后代码(变量r添加static修饰):

int *getRandom(void)
{
    static int r[10];

    srand((unsigned)time(NULL));
    for(int i;i < 10; i++)
    {
        r[i] = rand();
        printf("r[%d] = %d\n", i, r[i]);
    }

    return r;
}

编译、运行(OK):

lanfeiy@yelanfei ~/workspace/test
$ make -f c.mk
gcc -o pointerReturn pointerReturn.c -g -Wall

lanfeiy@yelanfei ~/workspace/test
$ ./pointerReturn.exe
r[1] = 533630443
r[2] = 261920408
r[3] = 1113003961
r[4] = 648006629
r[5] = 2060791236
r[6] = 641596662
r[7] = 972510164
r[8] = 1290130542
r[9] = 1687481754
*(p + 0) = 0
*(p + 1) = 533630443
*(p + 2) = 261920408
*(p + 3) = 1113003961
*(p + 4) = 648006629
*(p + 5) = 2060791236
*(p + 6) = 641596662
*(p + 7) = 972510164
*(p + 8) = 1290130542
*(p + 9) = 1687481754
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题