1
int *intAddr(){
  int i = 16;
  return &i;
}

char *charAddr(){
  char A = 'a';
  return &A;
}

然后我测试这两个功能

int *intaddr = intAddr();printf("%d\n", *intaddr);
char *charaddr = charAddr();printf(charaddr);

但结果是只有16个不是'a'。当函数 intAddr() 结束时,变量i被销毁。为什么*intaddr能得到16?

4

4 回答 4

4

You SHOULD NOT return a pointer to a variable that's function local. That's UNDEFINED BEHAVIOUR. DO NOT DO IT. EVER!!

The reason is that your local variable, i in this case, is destroyed when your function exits, so you pointer after your function exit will point to memory that contains at most junk.

于 2013-10-30T11:41:18.540 回答
1

Accessing a memory that is pointing to an element that is already destroyed invokes undefined behavior. What will happen is not defined and it is quite possible that different things happen if you run the code several times. What you do above is not much different from accessing just any address by the way.

于 2013-10-30T11:42:00.940 回答
0

This is just simply undefined behavior you are returning the address of an automatic variable, and so it won't exist once the function exits. Anything can happen with undefined behavior but it is not reliable. From the draft C++ standard section 6.7 Declaration statement paragraph 2 says:

Variables with automatic storage duration (3.7.3) are initialized each time their declaration-statement is executed. Variables with automatic storage duration declared in the block are destroyed on exit from the block (6.6).

于 2013-10-30T11:41:56.960 回答
0

改变这个

int *intAddr(){
int i = 16;
return &i;}

int *intAddr(){
int* i = new int(16);
return i;
于 2013-10-30T11:53:38.153 回答