c - 尝试获取指向 int 的指针时出现段错误

标签 c segmentation-fault

尝试运行下面的代码时出现段错误

#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/

相关文章:

c++ - 断言函数如何在失败时返回文件名和代码行

c指针段错误

C:字符串和指针。以特定模式更改字符串中的子字符串

java - Gradle:添加从 Java 到 Native 编译的依赖

c - 什么是有效的 TC (QoS) u32 过滤器句柄 ID

c++ - 当(CUDA 7.5 的)nvcc/cudafe++ 因段错误而崩溃时我该怎么办?

c - 当我尝试读取动态分配的数组内容时,为什么我的 C 代码会出现 "segmentation fault"错误?

c - 使用字符串 C 程序/Popen 时出现段错误

c++ - 原始 static_vector 实现中可能未定义的行为

objective-c - 结构体中的 __unsafe_unretained