[英]Segmentation fault in my program
#include<stdio.h>
#include<stdlib.h>
void memory_allocate(int *ptr)
{
ptr=(int*)malloc(sizeof(int)*100);
}
int main()
{
int *ptr1;
memory_allocate(ptr1);
*ptr1=12;
}
我的代码导致分段错误。 有人可以解释为什么吗?
问题在于,当函数设置ptr
,新的指针值不会传递回ptr1
。
一种实现此目的的方法是使用指向指针的指针:
void memory_allocate(int** ptr)
{
(*ptr) = (int*)malloc(sizeof(int)*100);
}
int main()
{
int *ptr1;
memory_allocate(&ptr1);
*ptr1=12;
/* TODO: free memory here */
}
您在分配内存时分配给ptr
的本地副本。 在memory_allocate函数外部不可见。
参数总是在C中按值传递。即使您似乎在“将指针传递给函数”,实际上也正在将指针的值传递给函数(存储在变量ptr1
内的地址的值),而不是指针本身。
因此,您可以想象这在功能上类似于:
int main()
{
int *ptr1;
// pass the value of ptr1 to memory_allocate
{
var tmp = ptr1;
// this doesn't change the original variable
tmp = malloc(sizeof(int) * 100);
}
*ptr1 = 12;
}
这并不意味着您不能更改存储在该地址的值,因为您可以轻松地在函数内部取消引用指针,但这意味着您永远无法更改原始变量的值, 除非您将指针传递给实际变量。到您的功能,如上面的@NPE所述。
以下建议的代码:
现在的代码:
#include <stdio.h> // perror()
#include <stdlib.h> // malloc(), free(), exit(), EXIT_FAILURE
// prototypes
void memory_allocate(int **ptr);
void memory_allocate(int **ptr)
{
*ptr = malloc(sizeof(int)*100);
if( !ptr )
{
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
}
int main( void )
{
int *ptr1 = NULL;
memory_allocate(&ptr1);
*ptr1=12;
free( ptr1 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.