malloc() & free()

3 main types of memory:

  • Data Segment
    • static code, globals, static
  • Stack
    • automatic local variables
  • Heap
    • dynamic, unknown until runtime

If the variables are not known until runtime, they cannot be allocated storage in the Data segment or Stack, since the compiler doesn't know how many variables there might be.

 

Therefore Dynamic Memory Management is utilised to allocate storage space at run time, as and when needed.

 

The malloc() and free() functions perform this functionality and are part of the stdlib.h, standard library header.

 

Therefore requires #include <stdlib.h>

 

malloc() returns a void pointer to the allocated memory, and requires the amount of memory required as its argument ( the sizeof() function is commonly used for this purpose).

 

Returns a NULL pointer if there's an error.

 

Must be removed at the end of its use, by use of free(), to stop memory leaks.

 

This example asks the user to enter the number of random characters to generate:

/* malloc example: string generator*/
#include <stdio.h>
#include <stdlib.h>

int main () {

	int myInt ;
	char * myString ;

	printf ("How many letters do you want in the string? ") ;
	scanf ("%d", &myInt) ;

	myString = (char*) malloc(myInt + 1) ; //the sizeof() function could have been used in place of myInt + 1
	if (myString == NULL) {
		printf("Error Out Of Memory! \n") ;
		return 1;
	}

	for (int i = 0 ; i < myInt ; i++) {

		myString[i] = rand() %26 + 'a' ;
	}

	myString[myInt] = '\0' ; //terminating the string

	printf ("Random string: %s\n",myString);
	free (myString);

return 0;
}

Leave a Reply