You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The sizeof operator is commonly used in calls to dynamic memory allocation routines to calculate how much memory needs to be allocated. If the sizeof operator is used improperly, unintended amounts of memory may be allocated. This may lead to program defects with security implications, such as buffer overflows. Therefore, it is necessary to guarantee that the sizeof operator is used properly with regard to dynamic memory allocation routines.

Non-compliant Code Example 1

This piece of code incorrectly uses the sizeof operator. When applied to a pointer, the sizeof operator returns the size of the pointer, not the size of the block of space the pointer refers to. As a result the call to malloc will return a pointer to a block of memory equal in size to the size of a pointer (commonly 4 bytes). When the strcpy is called a heap buffer overflow will occur.

char *src = "hello, world";
char *dest = malloc(sizeof(src));
strcpy(dest, src);

Compliant Solution 1

Fixing this issue requires the programmer to recognize and understand how sizeof works. In this case if, changing the type of src to a character array will correct the problem 

char src[] = "hello, world";
char *dest = malloc(sizeof(src));
strcpy(dest, src);

Compliant Code Example 2

In general, correcting issues regarding improper use of the sizeof operator requires that the programmer have a solid understanding of how sizeof works. Consider the following data types and variables: 

struct test_struct {
  char c1,c2;
  int *integer_ptr;
};

char array[10];
char * pointer = malloc(10);
char character;
struct test_struct structure;
struct test_struct struct_array[10];

 
The following are the implementation specific results of using the sizeof operator on those data types:

sizeof(char)         /* 1  Byte  */
sizeof(character)    /* 1  Byte  */
sizeof(&character)   /* 4  Bytes */
sizeof(pointer)      /* 4  Bytes */
sizeof(array)        /* 10 Bytes */
sizeof(structure)    /* 8  Bytes */
sizeof(&structure)   /* 4  Bytes */
sizeof(struct_array) /* 80 Bytes */
  • No labels