指针不允许自动变量在函数调用后被删除。

huangapple go评论90阅读模式
英文:

Pointer don't lets auto variable to get deleted after the function call

问题

以下是翻译好的部分:

  1. "I got Segmentation fault (core dumped) from this code because int i=7; is an auto variable and after the function call it gets deleted." 翻译成:我从这段代码中得到了Segmentation fault (core dumped)的错误,因为int i=7;是一个自动变量,在函数调用之后被删除。

  2. "But when I use an extra pointer instead of referencing operator I do not get any error and get 7 as output. Why this pointer don't allow to delete variable i?" 翻译成:但是当我使用额外的指针而不是引用运算符时,我没有收到任何错误,输出的结果是7。为什么这个指针不允许删除变量i?

英文:

When I use a pointer instead of referencing operator in a function pointer do not allow auto variable to get deleted after function call.

I got Segmentation fault (core dumped) from this code because int i=7; is an auto variable and after the function call it gets deleted.

#include<stdio.h>

int *func() {
  int i = 7;
  return &i;
}

int main(void) {
  int *a;
  a = func();
  printf("%d", *(a));

  return 1;
}

But when I use an extra pointer instead of referencing operator I do not get any error and get 7 as output. Why this pointer don't allow to delete variable i?

#include<stdio.h>

int *func() {
  int i = 7;
  int *ip = &i;
  return ip;
}

int main(void) {
  int *a;
  a = func();
  printf("%d", *(a));

  return 1;
}

答案1

得分: 2

这两个程序存在未定义行为,因为在调用函数 func 后,尝试解引用一个无效指针,该指针不指向已存在的对象。

英文:

The both programs have undefined behavior because after calling the function func there is an attempt to dereference an invalid pointer that does not point to an existent object.

huangapple
  • 本文由 发表于 2023年3月8日 16:31:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定