Malloc

The Function malloc is most commonly used to attempt to “grab” a continuous portion of memory.

Example 1

#include <stdlib.h>
#include <stdio.h>
 
#define BUFFERSIZE 1024*1024
 
//first the structures are defined
typedef struct 
{
    unsigned int buffer1[BUFFERSIZE];
    unsigned int buffer2[BUFFERSIZE];
    char test[10];
}sample_buffer;
 
int main(int argc, char *argv[]) 
{
    unsigned int i;
    sample_buffer *mybuffer;
 
    //allocating memory for mybuffer with the exact size
    if (( mybuffer = (sample_buffer *) malloc( sizeof(sample_buffer) ) ) == NULL) 
    {
        printf("ERROR ALLOCATING mybuffer\n");
            free(mybuffer);
        return 0;
    }
 
    printf("finished malloc\n");
    // fill allocated memory with integers and read back some values
    for( i = 0; i < ( BUFFERSIZE); i = i + 1) 
        {
        mybuffer->buffer1[i] = i;
        mybuffer->buffer2[i] = i + 100;
        // print some of the last values
        if (i >= ( (BUFFERSIZE - 10 )) ) 
        {    
            printf("mybuffer->buffer2[%d]=%d\n", i, mybuffer->buffer2[i]);
        }
    }
    memcpy(mybuffer->test, "Chrys",6);
    printf("(C) 2006 by %s\n", mybuffer->test);
 
    //cleanup
    free(mybuffer);
 
    getchar();
 
    return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.