How do I concatenate const/literal strings in C?

前端 未结 17 1505
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  温柔的废话
    2020-11-22 00:10

    It is undefined behaviour to attempt to modify string literals, which is what something like:

    strcat ("Hello, ", name);
    

    will attempt to do. It will try to tack on the name string to the end of the string literal "Hello, ", which is not well defined.

    Try something this. It achieves what you appear to be trying to do:

    char message[1000];
    strcpy (message, "TEXT ");
    strcat (message, var);
    

    This creates a buffer area that is allowed to be modified and then copies both the string literal and other text to it. Just be careful with buffer overflows. If you control the input data (or check it before-hand), it's fine to use fixed length buffers like I have.

    Otherwise, you should use mitigation strategies such as allocating enough memory from the heap to ensure you can handle it. In other words, something like:

    const static char TEXT[] = "TEXT ";
    
    // Make *sure* you have enough space.
    
    char *message = malloc (sizeof(TEXT) + strlen(var) + 1);
    if (message == NULL)
         handleOutOfMemoryIntelligently();
    strcpy (message, TEXT);
    strcat (message, var);
    
    // Need to free message at some point after you're done with it.
    

提交回复
热议问题