Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use strncat without buffer overflow concerns?

I have a buffer, I am doing lot of strncat. I want to make sure I never overflow the buffer size.

char buff[64];

strcpy(buff, "String 1");

strncat(buff, "String 2", sizeof(buff));

strncat(buff, "String 3", sizeof(buff));

Instead of sizeof(buff), I want to say something buff - xxx. I want to make sure I never override the buffer

like image 899
jscode Avatar asked Aug 01 '11 20:08

jscode


1 Answers

This is the best way to do it. sizeof() just gives you size of the pointer to the data if you don't allocate it locally (you did allocate locally in this case but better to do it this way and it will work if the code is re-factored).

#define MAXBUFFSIZE 64

char buff[MAXBUFFSIZE];

buff[0] = 0;  // or some string

strncat(buff, "String x",MAXBUFFSIZE - strlen(buff) - 1);
like image 178
Hogan Avatar answered Sep 20 '22 12:09

Hogan