codescracker


c

C malloc()



« Previous Function Next Function »


malloc()

The malloc() function returns a pointer to the first byte of a region of memory of size size that has been allocated from the heap. If there is insufficient memory in the heap to satisfy the request, malloc() returns a null pointer. It is always important to verify that the return value is not null before attempting to use it. Attempting to use a null pointer will usually result in a system crash.

malloc() Syntax

Following is the syntax of the malloc() function :

#include<stdlib.h>
void *malloc(size_t size);

malloc() Example

Following function allocates sufficient memory to hold structures of type addr :

struct addr
{
	char name[40];
	char street[40];
	char city[40];
	char state[40];
	char zip[10];
};

struct addr *get_struct(void)
{
	struct addr *p;
	if((p = malloc(sizeof(struct addr))) == NULL)
	{
		printf("Allocation Error\n");
		exit(1);
	}
	return p;
}

« Previous Function Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test