strcpy and strcat cause problems sometimes

后端 未结 3 684
借酒劲吻你
借酒劲吻你 2021-01-26 22:10

hello I have a code like the one below

char *str ;

        strcpy(str, \"\\t<\");
        strcat(str, time);
        strcat(str, \">[\");
        strcat(s         


        
相关标签:
3条回答
  • 2021-01-26 22:22

    This is much simpler and error-free from buffer overflows:

    #define BUFFERSIZE 512
    char str[BUFFERSIZE];
    
    snprintf(str, BUFFERSIZE, "\t<%s>[%s](%s) $ ", time, user, baseName);
    
    0 讨论(0)
  • 2021-01-26 22:24

    strcpy and strcat are used to copy and concatenate strings to an allocated char array.

    Since str in not initilized you're writing somewhere in memory and this is bad because you're corrupting other data. It may work at that moment but sooner or later you'll program will crash.

    You should allocate memory when declaring str:

    char str[100];

    Also, strcat is not efficient as it needs to search for the string end to know where concatenate chars. Using sprintf would be more efficient:

    sprintf(str, "\t<%s>[%s](%s) $ ", time, user, baseName);

    Finally, if you can't guarantee the generated string will fit the array, you'd better use snsprintf.

    0 讨论(0)
  • 2021-01-26 22:26

    You don't allocate memory and you leave str uninitialized. All later writes are done through an uninitialized pointer that points "somewhere" - that's undefined behavior.

    You have to allocate (and later free) memory large enough to hold the resulting string:

    char *str = malloc( computeResultSizeSomehow() );
    if( str == 0 ) {
       // malloc failed - handle as fatal error
    }
    
    //proceed with your code, then
    
    free( str );
    
    0 讨论(0)
提交回复
热议问题