user1377944
user1377944

Reputation: 455

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);   
} 

Upvotes: 3

Views: 222

Answers (3)

unwind
unwind

Reputation: 399881

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.

Upvotes: 7

paquetp
paquetp

Reputation: 1651

Result is not a char*, you probably want %d for that

Upvotes: 0

Attila
Attila

Reputation: 28762

Here

sprintf(Buffer,"<tr><td>%s </td> <td> %s </td> <td>  %s </td></tr>",Name,Description,Result);    

you are passing Result (which is of type uint8_t) as a pointer to char array

This means that the integral value will be inrepreted as a pointer which most likely will point to memory not accessible for you -- hence the seg. fault. You need to replace the third %s with the appropriate formatting flag to print the value as integer

Note: do not use %d directly in this case as your uint8_t type is not guaranteed to be the same size as int (most likely is not). You could use %d if you cast the value of Result to an int first ((int)Result)

Upvotes: 1

Related Questions