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:
- To allocate space for an array in memory you use calloc()
- To allocate a memory block you use malloc()
- To reallocate a memory block with specific size you use realloc()
- To de-allocate previously allocated memory you use free()
That’s all for this tutorial.
you people have quality well explained info
this tutorial is excellent, great work , thanks alot………
Thanks a lot, this tutorial is explained malloc() as well as how to struct handle……..
Thanks so much!
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.
@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:
The link to the page and the possible solution here
Thanx……
Good work!
Thank you! This tutorial helped me a lot! I would recommend it a lot.
Thanks a lot. I would recommend it.
thanks…….
n keep it up
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
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;
}
thanks……..
good
thanks a lot for clear cut definitions
Thanks a lot…
good
excellent…………
Perfecto ! Appreciate this tutorial for helping me a lot ! Thank you very much 😉
nice.
Nice explanation 🙂
the way of explaining of topic is very nice..thanx a lot…..
great tutorial. thnks
nice to explain all the things i was so confused before to read it thanx a lot…
nice tutorials
Very good explanation, and easy to understand. Thank You.
[…] allocate memory using malloc() and forget to free it. this also cause the leakage of […]
hi,
I want to check whether a particular word is present in FILE or not.someone pls help
Regards
vinodh.s
Very very nice work …………. Thanks
Thanks for your tutorial. It helps me a lot.
Thank you .. the tutorial was excellent !!! nd so what i required!!
thanks! the explanation helped me create my program…
Nice and detailed explanation.Thank You so much.
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
excellent
thanks .. that’s helpful 🙂
really helpfull… tanks alot
hey ! great job! thanks!!
what if the allocated memory is not freed?