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?

2
  • What is prgpath? Please edit and show a minimal reproducible example and tell us which compiler and compiler flags you use. Commented Sep 26, 2022 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. Commented Sep 26, 2022 at 11:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.