سؤال

I have 32 GB of RAM on my system and want to read and keep a file of 15 GB in memory. When I tried to execute following code, the output was: "n read = 1073741824", which corresponds to exactly 1 GB, whereas it should have read bytes corresponding to size of file.

I checked even running the system resource manager, and that has an increase of exactly 1GB, which means that malloc has not allocated 17 GB of space as was expected.

With 64 bit system, I could have read upto 8TB (with 32 bit system it is 2GB or more specific 1.5 GB).

I am on 64 bit machine and OS, and I have already configured Visual C++ to build and execute 64 bit binaries by following the steps given at: Intel Link [Verified that it is 64 bits by checking the size of int - earlier it was 4 bytes, now it is 8 bytes]

What could I tweak in order to allocate and use memory larger than 1 GB?

#include <stdio.h>
#include <cstdlib>

#define PATH "C:\\train"
#define SIZE 17*1024*1024*1024

int main()
{
        FILE * fp = fopen(PATH, "r");
    char* buff = (char*)malloc(SIZE);
    int nRead = fread(buff, 1, SIZE,  fp);
    buff[nRead] = 0;
    printf("n read = %d\n", nRead);

    int a;
    scanf("%d" ,&a);
    return 0;
}
هل كانت مفيدة؟

المحلول

The problem is that 17*1024*1024*1024 is a literal of type int and int is four bytes wide on Windows. You are quite mistaken in your belief that int is 8 bytes wide in 64 bit Windows. It's not. It is 4 bytes wide. Clearly a 4 byte integer cannot hold the value you wish to put in it.

You need to use a 64 bit integer literal:

17*1024*1024*1024ull
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top