Printf ubuntu分段故障(核心转储)

时间:2012-12-15 16:53:57

标签: c ubuntu segmentation-fault printf

我有这段代码:

int a;
printf("&a = %u\n",(unsigned)&a);
printf("a\n");
printf("b\n");
printf("c\n");
printf("d\n");

我试图打印a变量的指针 但它在行printf("a\n");上失败并说Segmentation fault (core dumped)
输出:

&a = 134525024
Segmentation fault (core dumped)

当我从代码中删除行printf("&a = %u\n",(unsigned)&a);时,它的成功。 输出:

a
b
c
d

我的代码中包含哪些内容?

2 个答案:

答案 0 :(得分:0)

这可能是一个架构问题。我在OS X上运行它并运行良好:

#import <stdio.h>
int main()
{
    int a;
    printf("&a = %u\n",(unsigned int)&a);
    printf("a\n");
    printf("b\n");
    printf("c\n");
    printf("d\n");
}

但是,我在编译期间收到了警告:

warning: cast from pointer to integer of different size

我在64位机器上,所以我的64位指针不适合32位int。 尝试运行它,看看你得到了什么:

#import <stdio.h>
int main()
{
    int a;
    printf("unsigned %ld\n", sizeof(unsigned)); // sizes reported in bytes
    printf("int %ld\n", sizeof(int));           // same as unsigned
    printf("long %ld\n", sizeof(long));         // should fit a pointer
    printf("ptr %ld\n", sizeof(void*));         // size of a pointer
    printf("&a = %lu\n", (unsigned long)&a);    // should print out your pointer
    printf("&a = %p\n", &a);                    // the Right Way of doing things
}

输出:

unsigned 4
int 4
long 8
ptr 8
&a = 140734544742408
&a = 0x7fff508c0808

编辑:

万一你不知道,unsigned实际上意味着unsigned int。同样,long实际上意味着long int

此外,值是signed还是unsigned不会改变其物理大小,只会改变它的解释方式。你可以从前两张照片中看到它。

答案 1 :(得分:0)

我解决了我的问题。我只是重新安装我的ubuntu和vmware,现在它的工作。我不确定究竟是什么问题,但它解决了我的问题...: - )