[英]Returning pointer from a function
我試圖從函數返回指針。 但我得到分段錯誤。 有人請告訴代碼有什么問題
#include<stdio.h>
int *fun();
main()
{
int *ptr;
ptr=fun();
printf("%d",*ptr);
}
int *fun()
{
int *point;
*point=12;
return point;
}
在使用指針之前分配內存。 如果你沒有分配內存*point = 12
是未定義的行為。
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
你的printf
也錯了。 您需要取消引用( *
)指針。
printf("%d", *ptr);
^
雖然返回一個指向本地對象的指針是不好的做法,但它並沒有在這里引起kaboom。 這就是你遇到段錯誤的原因:
int *fun()
{
int *point;
*point=12; <<<<<< your program crashed here.
return point;
}
本地指針超出范圍,但真正的問題是取消引用從未初始化的指針。 點的價值是多少? 誰知道。 如果該值未映射到有效的內存位置,您將獲得SEGFAULT。 如果幸運的是它映射到有效的東西,那么你只是通過用你的作業覆蓋那個地方來破壞你的內存。
由於返回的指針立即被使用,在這種情況下,您可以放棄返回本地指針。 但是,這是不好的做法,因為如果在另一個函數調用在堆棧中重用該內存之后重用該指針,則程序的行為將是未定義的。
int *fun()
{
int point;
point = 12;
return (&point);
}
或幾乎完全相同:
int *fun()
{
int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
另一個不好的做法,但更安全的方法是將整數值聲明為靜態變量,然后它不會在堆棧上,並且可以安全地被另一個函數使用:
int *fun()
{
static int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
要么
int *fun()
{
static int point;
point = 12;
return (&point);
}
正如其他人所提到的,“正確”的方法是通過malloc在堆上分配內存。
在將值12賦值給整數指針時不分配內存。 因此它崩潰了,因為它沒有找到任何記憶。
你可以試試這個:
#include<stdio.h>
#include<stdlib.h>
int *fun();
int main()
{
int *ptr;
ptr=fun();
printf("\n\t\t%d\n",*ptr);
}
int *fun()
{
int ptr;
ptr=12;
return(&ptr);
}
據我所知,使用關鍵字new,與malloc(sizeof identifier)的功能相同。 下面的代碼演示了如何使用關鍵字new。
void main(void){
int* test;
test = tester();
printf("%d",*test);
system("pause");
return;
}
int* tester(void){
int *retMe;
retMe = new int;//<----Here retMe is getting malloc for integer type
*retMe = 12;<---- Initializes retMe... Note * dereferences retMe
return retMe;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.