I have the below code, where the compiler is complaining:
int len = strlen(prgpath);
char* ptr = strrchr(prgpath, '/');
char prgname[64];
memset(prgname, 0, sizeof(prgname));
if (ptr==NULL)
strcpy(prgname, prgpath);
else
strncpy(prgname, (ptr+1), len-(ptr-prgpath));
Compiler gives the below warning:
"This call to strcpy() and strncpy() contains a buffer overflow. The source string
has an allocated size of (unavailable) bytes, and the destination buffer is 64
bytes."
How should I replace the above "strcpy" and "strncpy" to resolve the warning. Should I use strlcpy or any other API's present?
prgpath? Please edit and show a minimal reproducible example and tell us which compiler and compiler flags you use.prgpathpoints to is potentially longer than 64 (the size if theprgnamebuffer ) and therefore a buffer overflow may occur. Try usingstrncpyin both cases and truncate the 3rd paramater ofstrncpytosizeof(prgname) - 1, then you won't get a buffer overflow, but you might end up with a truncated string which may cause other problems later.