c - Fedora 17 64 位上的 C GCC 变量数据损坏

标签 c gcc gdb memory-alignment memory-corruption

我正在创建一个临时缓冲区并使用 sprintf 将一个字符串复制到该缓冲区。然后我调用函数 analyzeRecordForPGDBOperation 将缓冲区作为参数传递。我使用 | 解析带有 strtok 的字符串作为分隔符。我看到一个奇怪的问题,codesite 的值后来被损坏,即使它在 switch case 2 中正确打印。当我在 case 3 和 case 4 中打印时,codesite 的值不正确。

我试图在 gdb 中使用 codesite 变量上的 watch 查看它的共振,我得到以下输出,但我不确定为什么会出现这个问题。

[root@pe1800xs64 trunk]# uname -r 3.9.10-100.fc17.x86_64

“GDB 的输出:”

Old value = "71663138", '\000' New value = "\000\061\066\066\063\061\063\070", '\000'

0x00000038f30939ee in __strcpy_sse2_unaligned () from /lib64/libc.so.6

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main() 
{
    char tmp[256];
    sprintf(tmp, "%s", "99|71663138|316DEA40C62D6BA40B3C0AA2FE06C457|1442319758");
    analyzeRecordForPGDBOperation(tmp);
    return 0;
}

void analyzeRecordForPGDBOperation(char *data)
{
    char tempBuff[256] = {'\0',};
    char park[16] = {'\0',};
    char codesite[16] = {'\0',};
    char key[24] = {'\0',};
    char timestamp[16] = {'\0',};
    int caseVal = 0;
    sprintf(tempBuff, "%s", data);
    char *p = strtok(tempBuff,"|");

    for (; p != NULL; p = strtok(NULL, "|"))
    {
        caseVal++;
        switch(caseVal)
        {
            case 1:
                sprintf(park, "%s", p);
                break;
            case 2:
                sprintf(codesite, "%s", p);
                //Value of codesite is printed correctly here
                printf("\nCodesite: %s\n", codesite);
                break;
            case 3:
                sprintf(key, "%s", p);
                //Value of codesite is corrupted
                printf("\nCodesite Case 3: %s\n", codesite);
                break;
            case 4:
                sprintf(timestamp, "%s", p);
                //Value of codesite is corrupted
                printf("\nCodesite case 4: %s\n", codesite);
                break;
            default:
                break;
       }
    }
}

输出:

[root@pe1800xs64 trunk]# ./a.out

analyzeRecordForPGDBOperation

Codesite: 71663138

Codesite Case 3:

Codesite case 4:

最佳答案

如果此 "316DEA40C62D6BA40B3C0AA2FE06C457" 是您需要在案例 3 上复制的值,则目标缓冲区 key 并不大足够的。

这会触发未定义的行为,这就是为什么您之后会在 codesite 中看到奇怪的结果,即使您没有直接修改它也是如此。

关于c - Fedora 17 64 位上的 C GCC 变量数据损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32603554/

相关文章:

python - Nixos:如何获得带有包中包含的调试信息的 python?

c - malloc的作用(正确使用malloc)

c - 使本地 HTTP 服务器无法从外部访问

c++ - 将 SOIL.lib 与 GCC 一起使用 - 添加符号时出错 : File format not recognised

c - 如何创建匹配来自不同文件夹的文件的 rake 规则?

linux - ARM 工具链构建

c - "cannot collect variable"?

c - 16 位旋转哈希

C:将 char* 附加到 char**

rust - 如何在 rust-gdb 中打印调用 Rust 函数的结果?