3

When I perform a strcpy to a char[]:

char buf[100];

strcpy(buf[], largeInput);

If largeInput is longer than 100 bytes we have a buffer overflow.

However I have a question, if buf, instead of being a char[] is a char pointer, would there be a buffer overflow as well?

I think, if largeInput is long enough, when copied to char *buf, it could reach a memory zone of another variable. However I'm not sure this is a vulnerability.

I used flawfinder and it accused such code of being a buffer overflow vulnerability

char *buf;

strcpy(buf, largeInput);

I'm just not sure if it is a false positive or not.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
BVCGAAV
  • 301
  • 1
  • 4
  • 11

2 Answers2

2

If we see just this part of code

char *buf;
strcpy(buf, largeInput);

it is undefined behavior because, you're trying to write into unitialized pointer.

even if you have allocated memory to buf previously, and the content of largeInput is more that that of the allocated space in buf, then , yes, it is UB, too. There is no way buf gets auto adjusted.

However, FWIW, you can always use strdup() to be on safer side.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • The code is not just that, I just put the part I was interested in. Let's pretend the pointer is initialized and largeInput is some large input provided to the program :) – BVCGAAV Nov 28 '15 at 12:51
2

If you want to support arbitrary sized inputs allocate memory for largeInput based on the size.

char* largeInput = "very long string...";
char *buf = malloc(strlen(largeInput) + 1);
strcpy(buf, largeInput);
/* do something with buf */
free(buf);
Angus Comber
  • 9,316
  • 14
  • 59
  • 107