Teachers Paradise School Supplies Teacher Resources Free Encyclopedia
Teachers Paradise FREE Teaching Resources
Home Arts Crafts Audio Visual Equipment Office Supplies Teacher Resources
Main Page | Edit this page

Malloc

malloc is a tool for allocating memory dynamically in the C programming language. Without malloc, memory allocation must be done "at once".

For example, if we wish to create an array of ten integers, without malloc we may say

int x[10];
/* statements */

With malloc we can merely create a pointer to the first element of the array and make this point to malloc'd memory.
int *x = malloc(sizeof(int)*10);

Now this does not seem to have gained us much, but the use of malloc allows us to perform the following
int *x;
/* statements */
x = malloc(sizeof(int)*10); /* Now we can use the array, where we
                               may not have needed to before */

or
int *x = malloc(sizeof(int)*2);
x[0]=2;
x[1]=3;
/* etc */
free(x); /* release the memory */
x = malloc(sizeof(int)*5); /* Now we have space for five integers */

With it's companion function realloc we can create dynamically sized arrays in C.



Pay for Educational Supplies & Teaching Supplies with Visa, Master Card, American Express, Discover or Paypal.
TeachersParadise.com HOME | Safe Shopping Guarantee | Help Desk
All trademarks & brands are the property of their respective owners.
Legal Notice 2000-2008 TeachersParadise.com, Inc. All Rights Reserved