I am relatively new to 'C' and would appreciate some insight on this topic.
Basically, I am trying to create a 16 MB array and check if the memory content is initialized to zero or '\0' or some garbage value for a school project.
Something like this:
char buffer[16*1024*1024];
I know there is a limit on the size of the program stack and obviously I get a segmentation fault. Can this somehow be done using malloc()?
You can initialize the memory with malloc like so:
#define MEM_SIZE_16MB   ( 16 * 1024 * 1024 )
char *buffer = malloc(MEM_SIZE_16MB * sizeof(char) );
if (buffer == NULL ) {
    // unable to allocate memory. stop here or undefined behavior happens
}
You can then check the values in memory so (note that this will print for a very very long time):
for (int i = 0; i < MEM_SIZE_16MB; i++) {
    if( i%16 == 0 ) {
        // print a newline and the memory address every 16 bytes so 
        // it's a little easier to read
        printf("\nAddr: %08p: ", &buffer[i]); 
    }
    printf("%02x ", buffer[i]);
}
printf("\n");  // one final newline
Don't forget to free the memory when finished
free(buffer);
                        Yes, you will probably need to do this using malloc(), and here's why:
When any program (process ... thread ...) is started, it is given a chunk of memory which it uses to store (among other things ...) "local" variables. This area is called "the stack." It most-certainly won't be big enough to store 16 megabytes.
But there's another area of memory which any program can use:  its "heap."  This area (as the name, "heap," is intended to imply ...) has no inherent structure: it's simply a pool of storage, and it's usually big enough to store many megabytes.  You simply malloc() the number of bytes you need, and free() those bytes when you're through.
Simply define a type that corresponds to the structure you need to store, then malloc(sizeof(type)). The storage will come from the heap. (And that, basically, is what the heap is for ...)
Incidentally, there's a library function called calloc() which will reserve an area that is "known zero."  Furthermore, it might use clever operating-system tricks to do so very efficiently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With