当我改变函数中我调用malloc的位置时,出现分段错误。 此代码正常工作并打印“结束\ n”。从哪里调用malloc从哪里来都没关系? - c
#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;
}
但是,这个看似等价的代码在分段错误的“点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;
}
我在想什么? (我是一个初学者)
其他信息:我在Ubuntu下使用gcc使用Netbeans。
首先阅读如何使用'malloc'! – haccks
我读了其他东西,其中包括http://www.cplusplus.com/reference/cstdlib/malloc/的参考页面。对不起,这个愚蠢的错误,但我想我分配4个字节(我的系统中的一个int的大小),然后将指针指向该位置指向我的指针,然后检查它是否为null,以防万一。也许其他新手也有同样的困惑。 – niic