我正在创建一个临时缓冲区,并使用sprintf将一个字符串复制到缓冲区。然后调用传递缓冲区的函数analyzeRecordForPGDBOperation作为参数。我用strtok作为分隔符来解析字符串。我发现了一个奇怪的问题
我试图使用codesite变量的手表在gdb中看到它的reson,我得到了以下输出,但我不知道为什么会出现这个问题。
根@pe1800xs64 trunk# uname -r 3.9.10-100.fc17.x86_64
“GDB的产出:”
旧值= "71663138",'\000‘新值=“\000\061\066\066\063\063\070”,'\000’ __strcpy_sse2_unaligned ()中的0x00000038f30939ee来自/lib64 64/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;
}
}
}输出:
根@pe1800xs64 trunk# ./a.out analyzeRecordForPGDBOperation 代号: 71663138 Codesite案例3: Codesite案例4:
发布于 2015-09-16 08:50:33
如果这个"316DEA40C62D6BA40B3C0AA2FE06C457"是您需要在case 3上复制的值,那么目标缓冲区key就不够大。
这将触发未定义的行为,这就是为什么您在codesite中看到了奇怪的结果,即使您没有直接修改它。
发布于 2015-09-16 08:54:53
我分配的缓冲区的大小较小。缓冲区大小为24,而我试图复制33个字符到它。因此,内存被破坏了。随着新尺寸的增加,问题得到了解决。
char codesite16 = {'\0',};char key35 ={‘0’,};
谢谢你的帮助
https://stackoverflow.com/questions/32603554
复制相似问题