尝试运行下面的代码时出现段错误
#include <stdio.h>
int main(){
int* tes1;
int* tes2;
*tes1=55;
*tes2=88;
printf("int1 %p int2 %p \n",tes1,tes2);
return 0;
}
这是为什么?
最佳答案
你需要分配指针,否则它们指向垃圾内存:
int* tes1; //random initial value
int* tes2; //random initial value
为了使它们指向可分配的内存,使用malloc
函数:
int* tes1 = malloc(sizeof(int)); //amount of memory to allocate (in bytes)
int* tes2 = malloc(sizeof(int));
然后你安全地使用指针:
*tes1=55;
*tes2=88;
但是当你完成后,你应该使用 free
函数释放内存:
free(tes1);
free(tes2);
这会将内存释放回系统并防止内存泄漏。
关于c - 尝试获取指向 int 的指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15858777/