Segmentation fault using strcat

前端 未结 5 1638
孤独总比滥情好
孤独总比滥情好 2020-12-04 03:16

Here is my code :

char *name, name_log=\"log-\";

------getting \'name\' from user-----

strcat(name_log, name);
char ext[] =         


        
5条回答
  •  时光说笑
    2020-12-04 04:01

    For a start, if this is your code:

    char *name, name_log="log-";
    

    then name_log is a char, not a char pointer.

    Assuming that's a typo, you cannot append to string literals like that. Modifications to string literals are undefined behaviour.

    For a variable sized string, as user appears to be, probably the safest option is to allocate another string large enough to hold the result, something like:

    char *name, *name_log = "log-", *ext = ".log";
    // Do something to allocate and populate name
    char *buffer = malloc (strlen (name_log) + strlen (name) + strlen (ext) + 1);
    if (buffer == NULL) {
        // Out of memory.
    } else {
        strcpy (buffer, name_log);
        strcat (buffer, name);
        strcat (buffer, ext);
        // Do something with buffer.
        free (buffer);
    }
    

    The malloc ensures you have enough space to do all the string operations safely, enough characters for the three components plus a null terminator.

提交回复
热议问题