Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Initialize a 16mb array in C

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

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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);
over 4 years ago · Santiago Trujillo Relatório

0

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 );
}
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda