Initialize a 16mb array in C

2.4k Views Asked by At

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()?

4

There are 4 best solutions below

5
On BEST ANSWER

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);
1
On

Sure:

int memSize = 16*1024*1024;
char* buffer = malloc( memSize );
if ( buffer != 0 )
{
    // check contents
    for ( i = 0; i < memSize; i++ )
    {
        if ( buffer[i] != 0 )
        {
            // holler
            break;
        }
    }


    free( buffer );
}
0
On

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.

7
On

Strictly speaking, code can not check if buffer is not zeroed without risking undefined behavior. Had the type been unsigned char, then no problem. But char, which may be signed, may have a trap value. Attempting to work with that value leads to UB.

char buffer[16*1024*1024];
// Potential UB
if (buffer[0])  ...

Better to use unsigned char which cannot have trap values.

#define N (16LU*1204*1204)
unsigned char *buffer = malloc(N);
if (buffer) {
   for (size_t i = 0; i<N; i++) {
     if (buffer[i]) Note_NonZeroValue();
   }
}

// Clean-up when done.
free(buffer);
buffer = 0;

The tricky thing about C is that even if char does not have a trap value, some smart compiler could identify code is attempting something that is UB per the spec and then optimize if (buffer[0]) into nothing. Reading uninitialized non-unsigned char data is a no-no.