-2

I want to initialize an array of size 1MB. So my goal is finally write that 1MB to a file. I am curious every time i use this formula it is giving less than 1mb.

int len = (1048576)/sizeof(int);
data = (int *) malloc(len);

What is correct way ? Thank you


Edit - As per the comments I have changed the code .

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

int main(int argc, char *argv[]) {
    int *data;
    int bytes = (1024*1024);
    data = (int *) malloc(bytes);
    for(int i=0;i<bytes;i++){
     data[i] = (int)rand();
     printf("%d",data[i]);
    }
    return 0;

}

After compiling it and I tried dumping the data like below

 mpicc -o a mpiFileSize.c

 ./a > dump.dat

Now I see the file size of dump.dat. Why its 2.5MB ? File Size in Mac

ajayramesh
  • 3,576
  • 8
  • 50
  • 75

2 Answers2

4

Try this

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

int main(int argc, char *argv[]) {
char *data;
int bytes = (1024*1024);
data = (char *) malloc(bytes);
for(int i=0;i<bytes;i++){
 data[i] = (char) rand();
 printf("%c",data[i]);
}
return 0;

}

You shoul use character instead of integer.

0

Although it was already properly answered. Just a plus to the answer, if one wants to choose the amount of MBs to allocate would make something like:

#include <malloc.h>

#define Mebabyte (1024 * 1024)

int main(int argc, char** argv)
{
    void* data = malloc(2 * Megabyte);
    
    // Do your work here...
    
    free(data);
    return 0;
}

If you wanted to allocate more than 2 MBs just change the 2. As already stated before do not use integers as it's going to have more than 1 byte of size. Instead use char or unsigned char. And as stated by another post, there's no need to cast the result of malloc since void* can be turned to a pointer to any type (and in fact it's done implicitly by the compiler).

see: Why does this code segfault on 64-bit architecture but work fine on 32-bit?