malloc [C++ Reference]
Keywords: c,mem,malloc
Date: 2009-06-17T17:23:39-0700

[[malloc]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## malloc

Syntax:

        #include <cstdlib>
        void *malloc( size_t size );

The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it. An example:

         typedef struct data_type {
           int age;
           char name[20];
         } data;

         data *bob;
         bob = (data*) malloc( sizeof(data) );
         if( bob != NULL ) {
           bob->age = 22;
           strcpy( bob->name, "Robert" );
           printf( "%s is %d years old\n", bob->name, bob->age );
         }
         free( bob );

NOTE that new/delete is preferred in C++ (as opposed to malloc/free in C).

Related Topics: calloc, delete, free, new, realloc

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •