Skip to content

February 16, 2013

How To Allocate Memory in C With malloc()

by noise

If you use pointers in C you must first allocate memory, before you will use the pointer.

To allocate memory in C we will use malloc() function which is defined in header. To free memory allocated with malloc() we will use free() function which is also located in header.

Example 1

See next example:

#include <stdio.h>
#include <stdlib.h>	// for malloc() and free() functions
 
#include <string.h>
 
int main(void) {
 
    char str1[9] = "a string";
 
    char *str2 = 0;	// it's safer to make str2 = 0
                        // which is usefull if we forget
                        // to alloc memory before we will
                        // use it
 
    str2 = (char*)malloc(9);	// will alocate memory
 
    strcpy(str2, str1);		// will copy str1 into str2
 
    printf("str1 value is = %s\n", str1);
 
    printf("str2 value is = %s\n", str2);
 
    free(str2);		// we deallocate memory allocated
                        // for str2
}

It’s safer to make the pointer equal to zero right when we’ve define it (in case we forgot to alloc we won’t write on other’s programs memory).

Don’t forget to deallocate memory after using the pointer, otherwise there will be memory leaks.

Example 2

In example 2 we use sizeof() function to find out how much space we must allocate. Please note that in first example we allocated (hardcoded) 9 characters for var2 variable.

To find out the size of array of char elements (in this case) we use sizeof() C function. Then we will allocate that number of chars for var2 variable.

#include <stdio.h>
#include <stdlib.h>	// for malloc() and free functions
 
#include <string.h>
 
int main(void) {
 
    char str1[9] = "a string";
 
    char *str2 = 0;	// it's safer to make str2 = 0
                        // which is usefull if we forget
                        // to alloc memory before we will
                        // use it
 
    str2 = (char*)malloc(sizeof(str1));	// will alocate memory
 
    strcpy(str2, str1);		// will copy str1 into str2
 
    printf("str1 value is = %s\n", str1);
 
    printf("str2 value is = %s\n", str2);
 
    free(str2);		// we deallocate memory allocated
                        // for str2
}

Always use this instead of first example.

Read more from C Noise

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments