malloc <ALLOC.H>
Allocates memory
Declaration:
void *malloc(size_t
size);
Remarks:
malloc allocates a block of size bytes from the memory heap.
It allows a
program to allocate memory explicitly as it's needed, and in
the exact
amounts needed.
The heap is used for dynamic allocation of variable-sized
blocks of memory.
Many data structures, such as trees and lists, naturally
employ heap memory
allocation.
Return Value:
On success, malloc returns a pointer to
the newly
allocated block of memory.
On error (if not enough space exists for
the new block),
malloc returns null. The
contents of the
block are left unchanged.
If the argument size == 0, malloc returns
null.
Example:
#include
<stdio.h>
#include
<string.h>
#include
<alloc.h>
#include
<process.h>
int main(void)
{
char *str;
/* allocate memory
for string */
if ((str = (char
*) malloc(10)) == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}
/* copy
"Hello" into string */
strcpy(str,
"Hello");
/* display string
*/
printf("String is %s\n", str);
/* free memory */
free(str);
return 0;
}
0 comments:
Post a Comment