我正在制作一个RAM eater程序,它在while循环中分配64MB,直到它填满了请求的数量,同时打印每个循环分配的内存的地址。它适用于内存分配,但不打印地址
我要粘贴所有代码,以便您可以跟踪变量的来源,并评论不起作用的行:
void eatRAM()
{
int pCount = 0,
input = 0,
megaByte = 1048576;
unsigned long long toEat = 0,
eaten = 0,
i = 0,
allocFragments = 64 * (unsigned long long) megaByte;
puts("How much RAM do you want to eat? (in Mega Bytes)");
printf("\n>> MB: ");
scanf("%d", &input);
if(input < 64)
{
allocFragments = input;
}
toEat = (unsigned long long)(input * megaByte);
char * pMemory[toEat / allocFragments];
printf("\n\nTotal to eat: %llu Bytes\n", toEat);
do
{
pMemory[pCount] = malloc(allocFragments);
if(pMemory[pCount] != NULL)
{
//NEXT LINE PRINTS:
// < a lot > Bytes were allocated succesfully in 0x00000000
printf("%llu Bytes were allocated succesfully in 0x%p\n", allocFragments, pMemory[pCount]);
for(i = 0; i < allocFragments; i++)
{
pMemory[pCount][i] = 'x';
}
pCount++;
eaten += allocFragments;
}
else
{
puts("\nThere was an error trying to allocate memory. Finishing eating loop\n");
break;
}
}
while (pMemory[pCount] != NULL && eaten < toEat);
puts("----------------------------------");
printf("Total eaten: %llu Bytes\n", eaten);
puts("Check your task manager!\n");
}
在那一行中,我尝试在pMemory [pCount]之前使用&amp;,*但是却找不到打印该地址的方法。
答案 0 :(得分:3)
你有声明:
unsigned long long … allocFragments = 64 * (unsigned long long) megaByte;
以及 对printf()
的调用
printf("%li Bytes were allocated succesfully in 0x%p\n", allocFragments, pMemory[pCount]);
使用此代码,您的问题是您将unsigned long long
(8个字节)传递给printf()
,但告诉它打印long
(4个字节),所以它使用了你提供的一些信息,但剩下的(主要是零)被解释为内存指针的一部分。
由于您正在使用MiB和GiB内存,而且您声称自己的空指针获得00000000
,因此您可能在32位系统上,并且因此,您有4个字节的指针,而您正在打印的指针实际上是allocFragments
更重要部分的零字节。
更新: printf()
现已更新为:
printf("%lli Bytes were allocated successfully in 0x%p\n", allocFragments, pMemory[pCount]);
从理论上讲,这应该可以解决问题。 ......它有comment它做了!...
顺便提一下,如果您使用GCC作为编译器,它应该警告您格式与要打印的值之间的类型不匹配。如果不是,您就不会使用它可以正确提供的警告。我通常使用这些选项进行编译 - 有时会打开一些额外的选项。
gcc -std=c11 -g -O3 -Wall -Wextra -Werror -Wmissing-prototypes \
-Wstrict-prototypes -Wold-style-definition …