从函数返回 this 指针
我正在尝试从函数返回指针。但我遇到了分段错误。有人请告诉代码有什么问题
#include <stdio.h>
int *fun();
main()
{
int *ptr;
ptr = fun();
printf("%d", *ptr);
}
int *fun()
{
int *point;
*point = 12;
return point;
}
I am trying to return a pointer from a function. But I am getting a segmentation fault. Someone please tell what is wrong with the code
#include <stdio.h>
int *fun();
main()
{
int *ptr;
ptr = fun();
printf("%d", *ptr);
}
int *fun()
{
int *point;
*point = 12;
return point;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尽管返回指向本地对象的指针是不好的做法,但它并没有导致这里的崩溃。这就是出现段错误的原因:
本地指针超出范围,但真正的问题是取消引用从未初始化的指针。积分的价值是多少?谁知道呢。如果该值未映射到有效的内存位置,您将收到 SEGFAULT。如果幸运的是它映射到有效的东西,那么您只是通过将分配给 12 覆盖该位置而损坏了内存
。由于返回的指针立即被使用,在这种情况下您可以不必返回本地指针。但是,这是不好的做法,因为如果在另一个函数调用重用堆栈中的内存后重用该指针,则程序的行为将是不确定的。
或者几乎相同:
另一种不好的做法但更安全的方法是将整数值声明为静态变量,这样它就不会在堆栈上并且不会被另一个函数使用:
或者
正如其他人提到的,“正确的方法是通过 malloc 在堆上分配内存。
Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:
The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.
Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.
or almost identically:
Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:
or
As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.
它不会在将值 12 分配给整数指针时分配内存。因此它崩溃了,因为它没有找到任何内存。
你可以试试这个:
It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.
You can try this:
据我所知,关键字 new 的使用与 malloc(sizeof 标识符) 的作用相对相同。下面的代码演示了如何使用关键字new。
To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.
在使用指针之前分配内存。如果不分配内存,
*point = 12
是未定义的行为。另外你的 printf 是错误的。您需要取消引用 (
*
) 指针。Allocate memory before using the pointer. If you don't allocate memory
*point = 12
is undefined behavior.Also your
printf
is wrong. You need to dereference (*
) the pointer.