英文:
Pointer don't lets auto variable to get deleted after the function call
问题
以下是翻译好的部分:
-
"I got
Segmentation fault (core dumped)
from this code becauseint i=7;
is an auto variable and after the function call it gets deleted." 翻译成:我从这段代码中得到了Segmentation fault (core dumped)
的错误,因为int i=7;
是一个自动变量,在函数调用之后被删除。 -
"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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论