繁体   English   中英

程序结果根据printf的使用而变化

[英]Program outcome changes depending on printf usage

这是造成此问题的代码;

#include <stdint.h>

#define HASHPRINT(STRING) printf(STRING ": %p\n", simple_hash(STRING))

uint32_t simple_hash(const char *string) {
    uint32_t hash;

    char buffer[4]; /* 4 bytes = 32 bits */
    const char *c;
    int i = 0;

    for(c=string; *c!=0; c++) {
        buffer[i] = *c;
        i++;
        if (i == 3) {
            i=0;
            printf("\nAdding %u to hash\n", *((uint32_t *)buffer));
            hash += *((uint32_t *)buffer);
            hash = hash ^ *((uint32_t *)buffer);
        }
    }

    if (i > 0) {
        hash += *((uint32_t *)buffer);
        hash = hash ^ *((uint32_t *)buffer);
    }

    return hash;
}

void main() {
    HASHPRINT("yasar");
    HASHPRINT("rasay");
    HASHPRINT("arsay");
    HASHPRINT("yasra");
    HASHPRINT("osman");
    HASHPRINT("ali");
    HASHPRINT("veli");
}

程序输出的变化取决于我是否注释掉第18行中的printf函数调用。

没有printf,我的程序将输出以下内容:

yasar: 7D90F834
rasay: 00000005
arsay: 00000003
yasra: 00000001
osman: 00000003
ali: 00000001
veli: 00000005

如果启用了printf功能,则会得到此输出;

Adding 2004050297 to hash
yasar: 0F2400A0

Adding 7561586 to hash
rasay: 78C921B4

Adding 7565921 to hash
arsay: 78C94C94

Adding 7561593 to hash
yasra: 78C92194

Adding 7172975 to hash
osman: 78DD7FAC

Adding 6909025 to hash
ali: 7842A494

Adding 7103862 to hash
veli: 78C3698C

我希望在两种情况下,计算得出的哈希值(在单词后打印出来,用:与单词分开)将是相同的。

我不知道这是什么原因。

我正在将MinX与gcc 4.8.1版本一起使用WinXp。

函数simple_hash()使用未初始化的hashbuffer[3] -难怪程序的输出会simple_hash()变化。

另请注意,转换规范%p不适合uint32_t参数-正确的例如

#include <inttypes.h>
#define HASHPRINT(STRING) printf(STRING": %08"PRIx32"\n", simple_hash(STRING))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM