简体   繁体   中英

Buffer overflow vulnerabilities with char[ ] and char *

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM