0

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?

Santosh Sahu
  • 2,134
  • 6
  • 27
  • 51
  • What is `prgpath`? Please [edit] and show a [MCVE] and tell us which compiler and compiler flags you use. – Jabberwocky Sep 26 '22 at 11:23
  • I think the compiler is basically telling you that the string `prgpath` points to is potentially longer than 64 (the size if the `prgname` buffer ) and therefore a buffer overflow may occur. Try using `strncpy` in both cases and truncate the 3rd paramater of `strncpy` to `sizeof(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. – Jabberwocky Sep 26 '22 at 11:30

0 Answers0