Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find errors in C function [closed]

Tags:

c

This function converts a Boolean value to a string. point out possible runtime bugs.

#define TRUE  1
#define FALSE 0

char* bool2Str(boolean x)
{
char result[5];

if (x == TRUE)
strcpy(result, "TRUE");

if (FALSE == x) 
strcpy(result, "FALSE");

return &(result[0]);
}
like image 373
KIO Avatar asked Dec 04 '25 06:12

KIO


1 Answers

  1. Buffer overflow: "FALSE" is 6 bytes including the null terminator which strcpy will dutifully write, but there's only space for 5.
  2. A local temporary is returned by address from the function, making the returned value unusable (except to test it against NULL I suppose).
  3. Values other than 0 or 1 will not write anything at all. This pales in comparison to the other two bugs.
like image 75
John Zwinck Avatar answered Dec 07 '25 01:12

John Zwinck