Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string literal handling

What's wrong with the following piece of code that the program crashes - give segmentation fault. I am using gcc.

uint8_t result = 1      

InsertRow("Name","Details of work",result);     

void InsertRow(char *Name, char *Description,uint8_t Result)   
{  
   char Buffer[500];  

   if(Result==1)   
      sprintf(Buffer,"<tr><td>%s </td> <td> %s </td> <td>  %s </td></tr>",Name,Description,Result);   
} 
like image 744
user1377944 Avatar asked Jan 27 '26 07:01

user1377944


1 Answers

You're using the %s formatting specifier for an argument of type uint8_t, this should be %u, and you should cast the value to unsigned int to match. This saves you from having to care about the exact type and adjust the formatter (as commenters suggest).

Also, it's hard for us to know that the buffer is large enough, of course. If you have it, you can use snprinf() to avoid this.

like image 168
unwind Avatar answered Jan 28 '26 20:01

unwind