TOC | Prev | Next

malloc

When you need memory, but don't know at compile-time how big it is,
you use malloc.

When you're done with the memory, you free the pointer.

malloc.c

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

int main( void ) {
    const char greeting[]     = "Hello, ";
    const char name[]         = "Just Enough C class";

    const size_t greeting_len = strlen( greeting );
    const size_t name_len     = strlen( name );

    const size_t bytes_needed = greeting_len + name_len + 1;

    char *message = malloc( bytes_needed );

    printf( "Before I malloc, sizeof(message) = %lu\n", sizeof(message) );

    strcpy( message, greeting );
    strcat( message, name );

    printf( "After I malloc, sizeof(message) = %lu\n", sizeof(message) );

    puts( message );

    free( message );

    printf( "After I free, sizeof(message) = %lu\n", sizeof(message) );

    return 0;
}
TOC | Prev | Next