Using malloc() Function in C

By: Abinaya Emailed: 1700 times Printed: 2205 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The malloc() function isn't limited to allocating memory for strings, of course; it can allocate space for any storage need. This function allocates memory by the byte. Recall that malloc()'s prototype is

void *malloc(size_t num);

The argument size_t is defined in STDLIB.H as unsigned. The malloc() function allocates num bytes of storage space and returns a pointer to the first byte. This function returns NULL if the requested storage space couldn't be allocated or if num == 0.

Listing below shows you how to use malloc() to determine the amount of free memory available in your system. This program works fine under DOS, or in a DOS box under Windows. Be warned, however, that you might get strange results on systems such as OS/2 and UNIX, which use hard disk space to provide "virtual" memory. The program might take a very long time to exhaust available memory.

Using malloc() to determine how much memory is free.

1: /* Using malloc() to determine free memory.*/
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5:
6: /* Definition of a structure that is
7:    1024 bytes (1 kilobyte) in size.) */
8:
9: struct kilo {
10:    struct kilo *next;
11:    char dummy[1022];
12: };
13:
14: int FreeMem(void);
15:
16: main()
17: {
18:
19:    printf("You have %d kilobytes free.\n", FreeMem());
20:    return(0);
21: }
22:
23: int FreeMem(void)
24: {
25:    /*Returns the number of kilobytes (1024 bytes)
26:    of free memory. */
27:
28:    int counter;
29:    struct kilo *head, *current, *nextone;
30:
31:    current = head = (struct kilo*) malloc(sizeof(struct kilo));
32:
33:    if (head == NULL)
34:       return 0;      /*No memory available.*/
35:
36:    counter = 0;
37:    do
38:    {
39:       counter++;
40:       current->next = (struct kilo*) malloc(sizeof(struct kilo));
41:       current = current->next;
42:    } while (current != NULL);
43:
44:    /* Now counter holds the number of type kilo
45:       structures we were able to allocate. We
46:       must free them all before returning. */
47:
48:    current = head;
49:
50:    do
51:    {
52:       nextone = current->next;
53:       free(current);
54:       current = nextone;
55:    } while (nextone != NULL);
56:
57:    return counter;
58: }
You have 60 kilobytes free.

ANALYSIS: Listing above operates in a brute-force manner. It simply loops, allocating blocks of memory, until the malloc() function returns NULL, indicating that no more memory is available. The amount of available memory is then equal to the number of blocks allocated multiplied by the block size. The function then frees all the allocated blocks and returns the number of blocks allocated to the calling program. By making each block one kilobyte, the returned value indicates directly the number of kilobytes of free memory. As you may know, a kilobyte is not exactly 1000 bytes, but rather 1024 bytes (2 to the 10th power). We obtain a 1024-byte item by defining a structure, which we cleverly named kilo, that contains a 1022-byte array plus a 2-byte pointer.

The function FreeMem() uses the technique of linked lists, which was covered in more detail on Day 15, "Pointers: Beyond the Basics." In brief, a linked list consists of structures that contain a pointer to their own type (in addition to other data members). There is also a head pointer that points to the first item in the list (the variable head, a pointer to type kilo). The first item in the list points to the second, the second points to the third, and so on. The last item in the list is identified by a NULL pointer member.


C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(4)


1. View Comment

char *s;
s=(char *) melloc(sizeof(char)*3);

whts the need of siseof() function there, when we know the size of char is 1. can i write like this melloc(1*3);


View Tutorial          By: URS at 2011-08-24 12:32:55
2. View Comment

First things first, you might want to use malloc(int size_t).
Second and more important is sizeof(char) gives you the size in bytes of a type, this might change someday, and this way you only need to recompile things out. "read about utf 8 and utf 16"
What sizeof does is actually search the type definition in a table and it sees "hmm this type is declared this way,"
Things get cooler with typedef.


View Tutorial          By: leon at 2012-05-02 19:00:56
3. View Comment

excellent

View Tutorial          By: amit gupta at 2012-07-03 12:31:31
4. View Comment

i have to write a calculator program for very very big numbers . i mean have to use char array and + and - doesnt mean here in char aarray and we have to use malloc!!! i dont know what exactly have to do!!! plz help me and tell me how i have use malloc & free for it????

View Tutorial          By: maryam at 2012-12-31 10:21:55

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Abinaya
How to compile a Java program - javac
The clone() Method in Java
Data Types in Java
JSP Example to connect to MS SQL database and retrieve records
faces-config.xml to DirectTraffic in the JSF Application
Enabling Expression Language Evaluation in JSP
Using malloc() Function in C
ActionErrors and ActionError in Struts
Open, Creat, Close, Unlink system calls sample program in C
Structures and Functions in C
Introduction to JSP expression language
Multi-dimensional Arrays in C (Explained using date conversion program)
A C program similar to grep command in UNIX
Type Conversions in C (String to Integer, isdigit() etc)
Basics of C

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
Infix to Prefix And Postfix in C
Sorting an integer array in C
Line Counting sample program in C
External Variables and Scope in C
Relational and Logical Operators in C
Bitwise Operators in C
File Inclusion in C
union example program in C
scanf and sscanf sample program in C
Fopen and Getc implementation program in C
Using malloc() Function in C
Bitwise Logical Operators in C
Using the qsort() and bsearch() functions with values - example program in C
The C Character Set
Most Emailed Articles (in C)
Functions returning non-integer values in C
File Copying in C
Type Conversions in C (String to Integer, isdigit() etc)
Conditional Expressions in C
A C program similar to grep command in UNIX
Initialization of Pointer Arrays in C
Standard Input and Output in C
Bitwise Logical Operators in C
Printing a simple histogram in C
Find square and square root for a given number in C
The Birth and history of C Programming Language
Basics of C
Getting Started with C
Variables and Arithmetic Expressions in C
The for statement in C