Segmentation fault using strcat

前端 未结 5 1646
孤独总比滥情好
孤独总比滥情好 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 03:50

    A completely different solution would be this:

    const char *prefix = "log-";
    const char *suffix = ".log";
    // There's a "char *name" somewhere
    int size_needed;
    char *result;
    
    size_needed = snprintf(NULL, 0, "%s%s%s", prefix, name, suffix);
    result = malloc(size_needed + 1);
    snprintf(result, size_needed + 1, "%s%s%s", prefix, name, suffix);
    
    // "result" now contains the desired string.
    

    The nice thing about snprintf is that it returns the number of characters it would write if there was enough space. This can be used by measuring upfront how much memory to allocate which makes complicated and error-prone calculations unnecessary.

    If you happen to be on a system with asprintf, it's even easier:

    char *result = NULL /* in case asprintf fails */;
    asprintf(&result, "log-%s.log", name);
    // "result" must be released with "free"
    

提交回复
热议问题