How to convert current strcpy to strcpy_s?

I have a big project using everywhere strcpy. I think to use strcpy_sinstead strcpy. I think I used it almost 10,000 times strcpy. It is so cumbersome to change everyone strcpy. Is there an effective way to convert?

+4
source share
3 answers

You really should not do this without checking, since the buffer control tightening point is lost if not done reasonably.

Since the nature of the destination buffer (e.g. static or heap allocation, for example) is very important when it comes to the correct arguments for strcpy_s(), and this information is of course missing from an existing call, strcpy()you must add it in some way. It requires a person.

Often a type call strcpy(dest, src);can be converted to strcpy_s(dest, sizeof dest, src);, but if destallocated as a heap, it will just be the size of the pointer, not the pointed buffer, which of course is incorrect.

+4
source

Given that you have provided an additional parameter that cannot be inferred ( size_t destsz), which is necessary to be exact in order to benefit from the change, you are having a real problem.

10 000 strcpy() , , .

/ , , , . ( , , , ..). , , , .

" ", .

, filename , 255 ( NUL), strcpy(filename, () strcpy_s(filename,FILENAME_MAX_SZ.

"", .

strcpy(v, strcpy_s(v,SIZE_MAX ( ) - , , script. !;)

C11 _Generic, - :

#define __STDC_WANT_LIB_EXT1__

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int strcpy_s(char *dest,size_t destsz,const char *src){
    if(strlen(src)>=destsz){
        return 1;
    }
    strcpy(dest,src);
    return 0;
}

char *d_strcpy(char *dest,const char *src){
#ifndef NDEBUG
 fprintf(stdout,"unsafe copy of %s\n",src);
#endif
    return strcpy(dest,src);
}


#define strcpy(dest,src) _Generic (dest,\
    char[100] : strcpy_s(dest,sizeof dest,src),\
    char*: d_strcpy(dest,src)\
    )

int main(void) {
    char a[100]={'A','B','\0'};
    char *b=malloc(10*sizeof(char));

    strcpy(a,"XXX");
    strcpy(b,"XYX");

    printf("%s %s\n",a,b);

    free(b);
    return 0;
}

, , , , " ", Clang (untested), GCC, , ! . : N1930 ( _Generic)

.

+1

strcpy()? strcpy. strcpy_s, . , :

  • ?
  • ? ?
  • ? ?

- strcpy , -, .

0

Source: https://habr.com/ru/post/1676236/


All Articles