C Tutorial – The functions malloc and free

The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory.

When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.

Take a look at the following example:


	#include<stdio.h>

	int main()
	{
		int *ptr_one;

		ptr_one = (int *)malloc(sizeof(int));

		if (ptr_one == 0)
		{
			printf("ERROR: Out of memory\n");
			return 1;
		}

		*ptr_one = 25;
		printf("%d\n", *ptr_one);

		free(ptr_one);

		return 0;
	}

Note: If you compile on windows the windows.h file should be included to use malloc.

The malloc statement will ask for an amount of memory with the size of an integer (32 bits or 4 bytes). If there is not enough memory available, the malloc function will return a NULL. If the request is granted a block of memory is allocated (reserved). The address of the reserved block will be placed into the pointer variable.

The if statement then checks for the return value of NULL. If the return value equals NULL, then a message will be printed and the programs stops. (If the return value of the program equals one, than that’s an indication that there was a problem.)

The number twenty-five is placed in the allocated memory. Then the value in the allocated memory will be printed. Before the program ends the reserved memory is released.

Malloc and structures

A structure can also be used in a malloc statement.

Take a look at the example:


	#include<stdio.h>

	typedef struct rec
	{
    		int i;
    		float PI;
    		char A;
	}RECORD;

	int main()
	{
    		RECORD *ptr_one;

    		ptr_one = (RECORD *) malloc (sizeof(RECORD));

    		(*ptr_one).i = 10;
    		(*ptr_one).PI = 3.14;
    		(*ptr_one).A = 'a';

    		printf("First value: %d\n",(*ptr_one).i);
    		printf("Second value: %f\n", (*ptr_one).PI);
    		printf("Third value: %c\n", (*ptr_one).A);

    		free(ptr_one);

    		return 0;
	}

Note: the parentheses around *ptr_one in the printf statements.
This notation is not often used. Most people will use ptr_one->i instead. So (*ptr_one).i = 25 and ptr_one->i = 25 are the same.

If you want to use the structure without the typedef the program will look like this:


	#include<stdio.h>

	struct rec
	{
    		int i;
    		float PI;
    		char A;
	};

	int main()
	{
		struct rec *ptr_one;
		ptr_one =(struct rec *) malloc (sizeof(struct rec));

		ptr_one->i = 10;
    		ptr_one->PI = 3.14;
    		ptr_one->A = 'a';

    		printf("First value: %d\n", ptr_one->i);
    		printf("Second value: %f\n", ptr_one->PI);
    		printf("Third value: %c\n", ptr_one->A);

    		free(ptr_one);

   		return 0;
	}

One last tip before we end the tutorial: Always use sizeof. Never use this notation malloc(4). (Requesting 4bytes for the integer in the examples). This will make your code much more portable.

If you look at the dynamic memory functions of the stdlib.h library you will see that there are more functions that you can use to allocate dynamic memory. The following four dynamic memory functions can be found in the stdlib.h library:

That’s all for this tutorial.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 39 responses to “C Tutorial – The functions malloc and free”

Why not let us know what you think by adding your own comment!

  1. ruth on September 16th, 2009:

    you people have quality well explained info

  2. vikash on September 24th, 2009:

    this tutorial is excellent, great work , thanks alot………

  3. Nishan senevirathna on November 21st, 2009:

    Thanks a lot, this tutorial is explained malloc() as well as how to struct handle……..

  4. bob on February 6th, 2010:

    Thanks so much!

  5. Kenji on February 8th, 2010:

    Hi guys, i know this may not be related but i urgently need help from your expertise, hoping to seek advices from you.

    im trying to declare things like,

    char *TTLSnote[] = {“C1″,”C1″,”G1″,”G1″,”A1″,”A1″,”G2″,”F1″,”F1″,”E1″,”E1″,”D1″,”D1″,”C2”,
    “G1″,”G1″,”F1″,”F1″,”E1″,”E1″,”D2″,”G1″,”G1″,”F1″,”F1″,”E1″,”E1″,”D2”,
    “C1″,”C1″,”G1″,”G1″,”A1″,”A1″,”G2″,”F1″,”F1″,”E1″,”E1″,”D1″,”D1″,”C2″,”END”};

    and i got ERROR L107: ADDRESS SPACE OVERFLOW and ‘DATA’: SEGMENT TOO LARGE during compilation. Anyone may help?
    btw, im using Keil C51 compiler. Many thank in advance.

  6. admin on February 9th, 2010:

    @kenji First of, I never used the Keil C51 compiler. The declaration looks fine (and also is good in VC2008 compiler.)

    I found the following on keil compiler website:

    This error message indicates that a segment named ?CO?MAIN, which is a COnstant in the MAIN segment, is 8000h bytes long and will not fit in the remaining CODE memory space. This may be an indication that your program is growing too large or it may indicate that you need to increase the amount of ROM or RAM space available to your target hardware.

    The link to the page and the possible solution here

  7. Vidhya on August 29th, 2010:

    Thanx……
    Good work!

  8. Hugo I. Ramirez on October 3rd, 2010:

    Thank you! This tutorial helped me a lot! I would recommend it a lot.

  9. sadun on November 20th, 2010:

    Thanks a lot. I would recommend it.

  10. ruhi sharma on February 3rd, 2011:

    thanks…….
    n keep it up

  11. vimal on June 28th, 2011:

    char *TTLSnote = {“C1″,”C1″,”G1″,”G1″,”A1″,”A1″,”G2″,”F1″,”F1″,”E1″,”E1″,”D1″,”D1″,”C2″,
    “G1″,”G1″,”F1″,”F1″,”E1″,”E1″,”D2″,”G1″,”G1″,”F1″,”F1″,”E1″,”E1″,”D2″,
    “C1″,”C1″,”G1″,”G1″,”A1″,”A1″,”G2″,”F1″,”F1″,”E1″,”E1″,”D1″,”D1″,”C2″,”END”};
    dis is correct format… whn using dynamic initialization,,, dnt write *TTLSnote[],,
    avoid [] symbols

  12. Joseph on August 10th, 2011:

    I am attempting to read in data from a csv file with two columns: the first I am reading in as character string; the second column as a float. The column headers have been removed. I represent each row as atruct rec; the entire data should then be represented by an array of structs. My problem is that in the while loop I get segment fault when attempting to read the first row. Can anyone see why? Thanks.

    #include
    #include
    #define MAXROWS 400

    struct rec{
    char *date;
    float *yld;
    };

    struct rec *readFile();

    /* read the input file */
    struct rec *readFile(char *filname){
    FILE *fp;
    char *line;
    struct rec rw;
    int i=0;
    struct rec *data[MAXROWS];
    for(i = 0; i < MAXROWS; i++){
    data[i] = (struct rec *)malloc(sizeof(struct rec));
    }
    i = 0;
    rw = *data[0];
    if((fp = fopen(filname, "r")) != NULL){
    while(fscanf(fp, "%s,%f", rw.date, rw.yld) == 2){
    i++;
    rw = *data[i];
    }
    return data;
    }else{
    exit(1);
    }
    return NULL;
    }

    int main(){

    struct rec *data;
    data = readFile("temp_test.csv");
    return 0;
    }

  13. neeraj on November 14th, 2011:

    thanks……..

  14. Deepak on January 14th, 2012:

    good

  15. venkatesh on March 31st, 2012:

    thanks a lot for clear cut definitions

  16. mani on April 25th, 2012:

    Thanks a lot…

  17. jamshed on May 4th, 2012:

    good

  18. bharat on October 16th, 2012:

    excellent…………

  19. Xerxes on October 16th, 2012:

    Perfecto ! Appreciate this tutorial for helping me a lot ! Thank you very much 😉

  20. vignesh.p on October 26th, 2012:

    nice.

  21. Nimish on November 8th, 2012:

    Nice explanation 🙂

  22. praveen kumar (bvicam) on November 19th, 2012:

    the way of explaining of topic is very nice..thanx a lot…..

  23. HEAVENZ on January 31st, 2013:

    great tutorial. thnks

  24. parveen on February 6th, 2013:

    nice to explain all the things i was so confused before to read it thanx a lot…

  25. Himanshu pratap on February 14th, 2013:

    nice tutorials

  26. Sylvio Marcos B. C. on February 28th, 2013:

    Very good explanation, and easy to understand. Thank You.

  27. VALGRIND: Memory Saviour | Himanshu Gusain on March 24th, 2013:

    […] allocate memory using malloc() and forget to free it. this also cause the leakage of […]

  28. vinodh on April 21st, 2013:

    hi,
    I want to check whether a particular word is present in FILE or not.someone pls help

    Regards
    vinodh.s

  29. Khet kumar on May 2nd, 2013:

    Very very nice work …………. Thanks

  30. KY on June 18th, 2013:

    Thanks for your tutorial. It helps me a lot.

  31. Debolina on August 18th, 2013:

    Thank you .. the tutorial was excellent !!! nd so what i required!!

  32. jeet on September 27th, 2013:

    thanks! the explanation helped me create my program…

  33. Nikhil on October 15th, 2013:

    Nice and detailed explanation.Thank You so much.

  34. suresh on October 16th, 2013:

    Thank you, this is a good tutorial.
    also can you please refer if any material or books…i want to learn c in depth in a way that i can understand strucurtes, pointers and d.s in depth

  35. DILWAR KAPRWAN on December 12th, 2013:

    excellent

  36. beka on December 28th, 2013:

    thanks .. that’s helpful 🙂

  37. latha shree on January 19th, 2014:

    really helpfull… tanks alot

  38. Indhuja on February 23rd, 2014:

    hey ! great job! thanks!!

  39. DT Samrat on April 4th, 2014:

    what if the allocated memory is not freed?