【问题标题】:segmentation fault when trying to get the pointer to an int尝试获取指向 int 的指针时出现分段错误
【发布时间】:2013-04-07 04:12:33
【问题描述】:

尝试运行以下代码时出现分段错误

#include <stdio.h>


int main(){

    int* tes1;
    int* tes2;

    *tes1=55;

    *tes2=88;



    printf("int1 %p int2 %p \n",tes1,tes2);

    return 0;
}

这是为什么?

【问题讨论】:

  • 我不是不久前answer this吗? :p
  • 显然没有坚持,@chris
  • @scones,好吧,它不是同一个提问者,但它确实回答了为什么会有段错误。
  • @chris 好吧,根据搜索,段错误显然有 5,295 - 1 个原因。应该是一些冗余。
  • @Fazlan 当你的指针指向你不拥有的内存区域并使用它时(通过从操作系统请求它),你会得到一个段错误(或访问冲突)。

标签: c segmentation-fault


【解决方案1】:

需要分配指针,否则指向垃圾内存:

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);

这会将内存释放回系统并防止内存泄漏。

【讨论】:

    【解决方案2】:

    您正在声明指针,然后尝试定义指针的指针值

    #include <stdio.h>
    
    int main(){
    
        int* tes1;
        int* tes2;
        tes1=55; //remove the * here
        tes2=88;
        printf("int1 %p int2 %p \n",tes1,tes2);
    
        return 0;
    }
    

    【讨论】:

    • 如果他们想要它所指向的值是 55 或 88 怎么办?这就是我从问题中得到的意图。
    • 不,我很确定他是在声明指针,然后尝试将值分配给它们指向的内存。此外,您不能直接将整数值分配给指针。
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多