Use of sizeof() on a Pointer Type

From Guidance Share

Jump to: navigation, search

Contents

Description

Running sizeof() on a malloced pointer type will always return the (wordsize/8). Most of the time the developer is expecting size of the data that the pointer points to, not the pointer itself.

Applies To

  • Languages: C or C++
  • Operating platforms: Any

Example

The following code will print the size of a pointer, not the size of the underlying character buffer:

#include <stdiob.h>
int main(){
 char *foo = new char[255];
 printf("%d\n",sizeof(foo)); //this will return wordsize/4
 return 0;
}

Impact

Authorization: This error can often cause one to allocate a buffer much smaller than what is needed and therefore other problems like a buffer overflow can be caused.

Vulnerabilities

  • Use of sizeof() on a pointer when the size of the underlying data is actually desired.

Countermeasures

  • Implementation: Do not mistakenly use sizeof() on a pointer expecting the size of the underlying data to be returned.

Vulnerability Patterns

How Tos

Personal tools