C 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 :

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");
	return p;

C Online Test

« Previous Function Next Function »

Like/Share Us on Facebook 😋