nii*_*iic 0 c malloc segmentation-fault
当我改变我调用malloc的函数中的位置时,我遇到了分段错误.此代码工作正常并打印"结束\n".
#include <stdio.h>
#include <stdlib.h>
int main() {
int **pptr;
if (!( *pptr = malloc(4) ))
return 1;
int *ptr;
if (!( ptr = malloc(4) ))
return 1;
ptr[0]= 1;
printf("Point 1\n");
free(ptr);
(*pptr)[0] = 1;
free(*pptr);
printf("End\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,这个看似等效的代码在"Point 1 \n"之前从分段错误结束.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
if (!( ptr = malloc(4) ))
return 1;
ptr[0]= 1;
printf("Point 1\n");
free(ptr);
int **pptr;
if (!( *pptr = malloc(4) ))
return 1;
(*pptr)[0] = 1;
free(*pptr);
printf("End\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?(我有点初学者)
其他信息:我在Ubuntu下使用Netbeans,使用gcc.
在这两个程序中,您在此处调用未定义的行为:
int **pptr;
if (!( *pptr = malloc(4) ))
return 1;
Run Code Online (Sandbox Code Playgroud)
pptr是一个未初始化的指针,被取消引用以存储返回的指针malloc.由于未定义的行为,第一个恰好看起来像它正在工作,但正在破坏内存,pptr恰好指向.
第二个失败是因为pptr恰好指向了无法写入的内存区域.
另外,由于在上面的代码int*中正在分配,因此malloc(4)是不安全的.使用malloc(sizeof(int*)).例如,64位系统通常具有8字节指针.