Pointer accessing heap memory

Category: Overflow  

Definitions:

Buffer Overflow - When a program writes beyond the bounds of a buffer
Bounds Checking - The pointer is not allowed to access heap memory that does not belong to it.

What You Should Not Do

Allocate space in memory using malloc(), and then character pointer is assigned a value, beyond the space allocated.This can cause indeterminate program behavior (usually leading to a segfault), or hijack the program's flow.

char *ptr = (char*) malloc(10);              //initialise a buffer of size 10

ptr[10]='c';

The pointer is not allowed to access heap memory that does not belong to it.

What You Should Do

ALWAYS check the bounds of data stored in buffers.To make the above example safe, Array assignment should be between the indices 0-9.In this case the size of the array has been declared as 10 but the element is assigned to an index position of 10.Also malloc() may return a NULL pointer. Thus, a null check is necessary

char *ptr = (char*) malloc(10);              //initialise a buffer of size 10
if(ptr != NULL){
ptr[9]='c';
}

Concept Map

This example refers to the point F (Avoid calls to malloc() with the parameter (number of bytes to be allocated) set to 0.Either the function returns NULL, or it returns a pointer to space that cannot be used without overwriting unallocated memory).Hence providing a NULL check will prevent exception and memory being overwritten. This maps to the point number 2, which states that "Assume any input is going to be malformed or not what to expect".Further, if falls under the category of "Assumptions".

JSN Teki template designed by JoomlaShine.com