Main Content

Unreliable cast of pointer

Pointer implicitly cast to different data type

Description

This defect occurs when a pointer is implicitly cast to a data type different from its declaration type. Such an implicit casting can take place, for instance, when a pointer to data type char is assigned the address of an integer.

This defect applies only if the code language for the project is C.

Risk

Casting a pointer to data type different from its declaration type can result in issues such as buffer overflow. If the cast is implicit, it can indicate a coding error.

Fix

Avoid implicit cast of a pointer to a data type different from its declaration type.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Examples

expand all

 #include <string.h>
 
 void Copy_Integer_To_String()
 {
  int src[]={1,2,3,4,5,6,7,8,9,10};
  char buffer[]="Buffer_Text";
  strcpy(buffer,src);   
  /* Defect: Implicit cast of (int*) to (char*) */
 }

src is declared as an int* pointer. The strcpy statement, while copying to buffer, implicitly casts src to char*.

Correction — Avoid Pointer Cast

One possible correction is to declare the pointer src with the same data type as buffer.

 #include <string.h>
  void Copy_Integer_To_String()
 {
  /* Fix: Declare src with same type as buffer */
  char *src[10]={"1","2","3","4","5","6","7","8","9","10"};  
  char *buffer[10];

  for(int i=0;i<10;i++)
    buffer[i]="Buffer_Text";

  for(int i=0;i<10;i++)
    buffer[i]= src[i];
  }

Result Information

Group: Static memory
Language: C
Default: On
Command-Line Syntax: PTR_CAST
Impact: Medium

Version History

Introduced in R2013b