Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncat Wformat-overflow warning when using gcc 8.2.1

I'm using gcc 8.2.1 and trying to build this code:

std::string dir = "Documents";
char * _tempname = static_cast <char*> (malloc( dir.length() + 14));
strncpy (_tempname, dir.c_str(), dir.length()+1 );
strncat (_tempname, "/hellooXXXXXX", 13);

but it gives me this warning:

warning: 'char* strncat(char*, const char*, size_t)' specified bound 13 equals source length [-Wstringop-overflow=]

After searching I found that it's an overflow problem to have the size_t equals the source length according to the discussion in this link but I couldn't understand why this is considered a problem and why this overflows the destination. And how could I remove this warning without changing my code?

like image 352
Amr Essam Avatar asked Dec 07 '22 13:12

Amr Essam


1 Answers

Apparently GCC understands that strncat(_tempname, "/hellooXXXXXX", 13); is no different from strcat(_tempname, "/hellooXXXXXX");, and finds it suspicious that you're using former instead of the latter.

If you can change the code, use strcat instead (or even better, rewrite the thing to use std::string).

If you can't change the code, use -Wno-stringop-overflow flag to disable the warning.

like image 75
HolyBlackCat Avatar answered Dec 30 '22 04:12

HolyBlackCat