你能帮我解决下面的C问题吗?我试图打印一个包含30个连续值的列表,从某个内存地址开始。我想在每个内存位置打印1个字节作为十六进制。作为要插入的内存地址的指示,我在程序开始时打印虚拟地址。
问题是我得到的值超过1个字节。对于长序列的零,这仍然会产生00,但是一旦出现非零值,我就会得到一个4字节“窗口”的打印。这导致以下输出:
Main function address is 0x8048494
Dummy variable address is 0x9a2e008
Enter the address (without the 0x):9a2e008
You entered: 9a2e008
Address Byte value
0x9a2e008 00
0x9a2e009 00
0x9a2e00a 00
0x9a2e00b 00
0x9a2e00c 00
0x9a2e00d 00
0x9a2e00e 00
0x9a2e00f 00
0x9a2e010 00
0x9a2e011 f1000000
0x9a2e012 ff10000
0x9a2e013 20ff100
0x9a2e014 20ff1
0x9a2e015 3900020f
0x9a2e016 61390002
0x9a2e017 32613900
0x9a2e018 65326139
0x9a2e019 30653261
0x9a2e01a 30306532
0x9a2e01b 38303065
0x9a2e01c 383030
0x9a2e01d 3830
0x9a2e01e 38
0x9a2e01f 00
0x9a2e020 00
0x9a2e021 00
0x9a2e022 00
0x9a2e023 00
0x9a2e024 00
0x9a2e025 00
到目前为止我的代码是:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define NUMBER_OF_BYTES 10
void showAddresses(void);
void printMemoryAtAddress(void);
int * dummy;
int dumpSize = 30;
int main(void)
{
dummy = (int *) malloc (sizeof(int)); showAddresses();
printMemoryAtAddress();
return 0;
}
void showAddresses(void)
{
printf("Main function address is %p \n", main);
printf("Dummy variable address is %p \n",(void*)dummy);
}
void printMemoryAtAddress(void)
{
int input;
printf("Enter the address (without the 0x):");
scanf("%x", &input);
printf("You entered: %x \n", input);
printf("Address \tByte value \n");
int i;
for(i=0;i<dumpSize;i++)
{
int* address;
address = (int*) (input+i);
printf("%p \t", address);
printf("%.2x \n", *address);
}
}
非常感谢任何有关此问题的帮助!如果这个问题很愚蠢,我道歉。 (我还在学习,经过几个小时的尝试后似乎无法找到解决方案!) 乔
答案 0 :(得分:7)
你的问题在这里:
void printMemoryAtAddress(void)
{
int input;
printf("Enter the address (without the 0x):");
scanf("%x", &input);
printf("You entered: %x \n", input);
printf("Address \tByte value \n");
int i;
for(i=0;i<dumpSize;i++)
{
int* address;
address = (int*) (input+i);
printf("%p \t", address);
printf("%.2x \n", *address);
}
}
地址应该是unsigned char *而不是int *。作为int *,它将内存读取为整数,您希望将其读取为只有一个字节的char。
祝你好运!