Question

I know that the whole family of strcpy, strcat and strcmp have buffer overflow vulnerability, to mitigate the strcpy vulnerability someone can use the strlcpy, what about the strcat and strcmp, are there safe versions of that functions or someone have to check the variables manually?

Was it helpful?

Solution

I recommend about the str-n-func family:

Use strncpy instead of strcpy, strncat instead of strcat, strncmp instead of strcmp, and so on.

The additional n is for additional (third) parameter, that is as the maximal number of characters to copy/concatenate/compare.

Read about them here (with examples):

http://www.cplusplus.com/reference/cstring/strncmp/

http://www.cplusplus.com/reference/cstring/strncat/

Remarks:

  1. The functions strlcpy and strlcat are not standard.
  2. You should be careful, as (for example) copying at most n chars from a string with more than n characters (until the first null), will ended with a string that is not null-terminated.
  3. Usually, as a programmer, you have the option to know what is the length of the strings you deal with, and because the previous remark, even if you use str-n-functions you still need to know this.
  4. The problem is mainly in reading input into some final buffer. You must not use scanf or gets, and you can use fgets. For example: instead of using gets to read string from the standard input, use fgets as follows:

    fgets(str, sizeof(str), stdin);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top