【问题标题】:printf() prints the correct int value written to a pointer, but not the correct double value written to another. Why is that?printf() 打印写入指针的正确 int 值,但不打印写入另一个指针的正确 double 值。这是为什么?
【发布时间】:2016-03-01 11:56:57
【问题描述】:

我尝试声明两个变量,一个是int * 类型,一个是double * 类型,并为每个变量分配地址,但通过取消引用和打印分配显示int 的正确值,但打印0.0 为double .这是为什么?

#include <stdio.h>

int main(void)
{
    int *x;
    x = (int *)&x;
    *x = 3;
    //print val of pointer
    printf("%d\n", x);

    double *y;
    y = (double *)&y;
    *y = 4.0;
    printf("%lf\n", y);
    return 0;
}

【问题讨论】:

  • 在这两种情况下,您都在调用 未定义的行为 - 您不能指望会发生任何合理的事情。
  • 你从哪里想到的?
  • @MartinJames 我在 stackoverflow 的噩梦中看到了它,在那里我被否决了 3 次 :):)
  • 我认为这个问题很有趣并且足够清晰。 “疯狂的代码”没有密切的原因;-)。事实上,有什么问题比问“为什么我的完整源代码在下面的程序会产生输出 x?”更清楚。而UB与否,原因可以完美地显示出来。 许多关于 SO 的问题远不如。投票给绳子。
  • @Alex 我不确定我是否理解正确。 x 和 y 都没有被“使用此内存位置中的任何垃圾”(which 位置?)进行初始化。它们被初始化(好吧,在定义它们之后分配给它们)使用它们自己拥有的明确定义的地址(不是--未定义的-它们指向)。

标签: c pointers stack printf strict-aliasing


【解决方案1】:

我得到 4.0。

您所做的是将分配用于存储地址(x 和 y)的内存分别重新解释为 int 和 double。

您这样做了两次:当您将数据值分配给重新解释的内存时,以及当您打印它的副本时。这两种情况是不同的。

  1. 通过不兼容类型的指针写入内存是未定义的行为,并且已知像 gcc 这样的编译器在这种情况下会做一些有趣的事情(陷阱或忽略代码)。对此有曲折的讨论,包括 Linus Torvalds 的著名咆哮。它可能会也可能不会起作用。如果它有效,它可能会做预期的事情。 (对于正确的代码,您必须使用联合或执行 memcpy。)

    它工作的一个条件是您的数据类型不需要比指针更多的空间。在 32 位架构上(可能是 64 位 Intel CPU 的 32 位编译器),双精度将比 4 字节地址长(IEEE 754 双精度有 8 字节)。 *y = 4.0; 写入超出y 的内存,覆盖堆栈上的其他数据。 (注意y 指向它自己,所以分配给*y 会覆盖y 自己的内存。)

  2. 将指针值作为参数传递给printf,转换规范分别为%d%lf 也未定义。 (实际上,如果转换规范为%p 并且指针值未强制转换为void *,则它已经未定义;但这通常被忽略且与常见架构无关。) printf 将仅解释堆栈上的内存(这是一个副本的参数)作为一个int resp。双重身份。

为了理解发生了什么,让我们看一下 main 堆栈上的内存布局。我写了一个详细说明它的程序;来源如下。在我的 64 位 Windows 上,可以正确打印 4.0 的双精度值;指针变量y 大到足以容纳double 的字节,并且所有8 个字节都被复制到printf 的堆栈中。但是如果指针大小只有 4 个字节,那么只有这 4 个字节会被复制到 printf 的堆栈中,它们都是 0,并且超出该堆栈的字节将包含来自早期操作的内存或任意值,例如 0 ;-),哪个 printf 将读取以尝试解码双精度。

这是在各个步骤中对 64 位架构上的堆栈的检查。我用两个标记变量declStartdeclEnd 将指针声明括起来,这样我就可以看到内存在哪里。我会假设该程序也可以在 32 位架构上进行微小的更改。试试看,告诉我们你看到了什么!

更新:它在 ideone 上运行,它似乎有 4 个字节的地址。双重版本不打印 0.0 而是一些任意值,这可能是因为 4 个地址字节后面的堆栈垃圾。参照。 https://ideone.com/TJAXli.

上面输出的程序在这里:

#include <stdio.h>

void dumpMem(void *start, int numBytes)
{
    printf("memory at %p:", start);
    char *p = start;
    while((unsigned long)p%8){ p--;  numBytes++;}   // align to 8 byte boundary
    for(int i=0; i<numBytes; i++) 
    {
        if( i%8 == 0 ) printf("\nAddr %p:", p+i);
        printf(" %02x", (unsigned int) (p[i] & 0xff));
    }
    putchar('\n');
}

int len;        // static allocation, protect them from stack overwrites
char *from, *to;

int main(void)
{
    unsigned int    declStart = 0xaaaaaaaa; // marker
    int             *x = (int *)   0xbbbbbbbbbbbbbbbb;
    double          *y = (double *)0xcccccccccccccccc;
    unsigned int    declEnd = 0xdddddddd;   // marker

    printf("Addr. of x: %p,\n      of y: %p\n", &x, &y);

    // This is all UB because the pointers are not
    // belonging to the same object. But it should
    // work on standard architectures.
    // All calls to dumpMem() therefore are UB, too.
    
    // Thinking of it, I'd be hard-pressed to find 
    // any defined behavior in this program.
    if( &declStart < &declEnd ) 
    {
        from = (char *)&declStart;
        to = (char *)&declEnd + sizeof(declEnd);
    }
    else
    {
        from = (char *)&declEnd;
        to = (char *)&declStart + sizeof(declStart);
    }
    len = to - from;

    printf("len is %d\n", len);
    printf("Memory after initializations:\n");
    dumpMem(from, len);

    x = (int *)&x;
    printf("\nMemory after assigning own address %p to x/*x: \n", &x);
    dumpMem(from, len);
    
    *x = 3;
    printf("\nMemory after assigning 3 to x/*x: \n");
    dumpMem(from, len);

    //print val of pointer
    printf("x as long: %d\n", (unsigned long)x);

    y = (double *)&y;
    *y = 4.0;
    printf("\nMemory after assigning 4.0 to y/*y: \n");
    dumpMem(from, len);

    printf("y as float: %f\n", y);
    printf("y as double: %lf\n", y);
    printf("y as unsigned int: 0x%x\n", y);
    printf("y as unsigned long: 0x%lx\n", y);
    
    return 0;
}

【讨论】:

  • 很好的解释,这就是为什么我希望重新打开并正确回答这个问题。
【解决方案2】:

男孩,这是我最近看到的最奇怪的一段代码......

无论如何,如果您真的想弄清楚整个代码中发生了什么,最好的方法是使用调试器单步执行。以下是它在我的机器上的工作方式:

(gdb) break main
Breakpoint 1 at 0x400535: file test.c, line 6.
(gdb) run
...

Breakpoint 1, main () at test.c:6
warning: Source file is more recent than executable.
6           x = (int *)&x;
(gdb) n
7           *x = 3;
(gdb) p x
$1 = (int *) 0x7fffffffdab0
(gdb) n
9           printf("%d\n", x);
(gdb) p x
$2 = (int *) 0x7fff00000003
(gdb) n
3
12          y = (double *)&y;
(gdb) n
13          *y = 4.0;
(gdb) p y
$3 = (double *) 0x7fffffffdab8
(gdb) n
14          printf("%lf\n", y);
(gdb) p y
$4 = (double *) 0x4010000000000000
(gdb) n
0.000000
15          return 0;
(gdb) 

基本上,您正在做的是通过在过程中使用自己来弄乱指针值。在执行*x = 3; 时,您可以看到您通过写入 0x00000003 消除了x 的最低有效 32 位。之后,当您执行*y = 4.0; 时,您会用4.0 的内部双精度表示覆盖整个指针值。直觉上,第二个printf 应该打印4.0,所以我猜这个问题存在于printf 本身。如果你这样做:

double test;
memcpy(&test, &y, sizeof(double));
printf("%lf\n", test);

这将输出4.000000

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多