PHP Extensions: Understanding memory allocation

10 May

One of the nice features of c is that it allows you to allocate memory to the variables you use. It will not be a good practice to waste memory while handling several thousand or even million of request.

So before building PHP Extensions it will be better to understand how c take care of memory allocation.

Malloc

In order to use this function you will need to include stdlib.h in your program.

This function returns either memory address allocated or null in case no memory allocated.

An example can be

include “stdlib.h”

void main(void)

{

char *p;

p = malloc(500);

}

This example assigns 500 bytes of memory to pointer p. Here pointer can be of any pointer. The only exception come with malloc is null memory allocation.

Calloc

Another very useful function for allocating memory. This allocate memory similar to the malloc, however it is different from the malloc.

An example can be

char *p;

p = calloc(40, sizeof(char));

It takes two arguments.

  1. The number of element
  2. size of each element

Realloc

Another very usefull function.

An example can be

char *p;

p = realloc(NULL, 500);

Realloc is used to reallocate memory. If null is passed as first argument, realloc work as malloc.

char *pt;

pt = realloc(pt, 500);

this however work differently. Either allocate the memory previously allocated or give new memory, however in case new memory is allocated all the information from the old block is copied to the new location. A question come to front, why it assign new memory location?

Well, it depends. When you assign more memory allocation then it previously hold, and the memory at that location is not enough it will assign it new memory.

char *pt;

pt = realloc(pt, 0);

If zero is given, it frees the memory previously allocated and return a null pointer.

While working with memory allocation function, it is your job to free the memory allocated.

You can use free method. If you don’t free memory, a bug called memory leak can jumps out.

char *pt;

pt = malloc(500);

free(pt);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: