Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li>Yes, it is. There's no specific violations of the standard there. The <code>memset</code> is a waste of time however since it's al going to be overwritten anyway (make your first <code>strcat</code> into a <code>strcpy</code>). And you should <em>always</em> check for <code>malloc</code> returning NULL. <em>No matter what!</em></li> <li>C89/90 is not the current standard, C99 is. And C1x is not that far away. GCC is keeping up with the bleeding edge.</li> <li>Only use local arrays if you don't need them to survive beyond the end of the function. Otherwise <code>malloc</code> is your best bet, particularly if you want to <em>return</em> the combined string.</li> <li>I think gcc has the <code>-std=c89</code> flag or something similar. In any case, MSVC does not always follow the standard :-)</li> <li>Compile and test it on both platforms frequently. That's the only way to be sure.</li> </ol> <p>I would opt for:</p> <pre><code>void foo (const char *p1, const char *p2, const char *p3) { size_t length = strlen(p1) + strlen(p2) + strlen(p3); char *combined = (char *) malloc(length + 1); if (combined == NULL) { printf("Result : &lt;unknown since I could't get any memory&gt;\n"); } else { strcpy(combined, p1); strcat(combined, p2); strcat(combined, p3); printf("Result : %s", combined); free(combined); } } </code></pre> <p>or, since you're not actually doing anything with the string except printing it:</p> <pre><code>void foo (const char *p1, const char *p2, const char *p3) { printf("Result : %s%s%s", p1, p2, p3); } </code></pre> <p>:-)</p> <p>Another strategy I've seen is the "only allocate if you have to" strategy:</p> <pre><code>void foo (const char *p1, const char *p2, const char *p3) { char str1k[1024]; char *combined; size_t length = strlen (p1) + strlen (p2) + strlen (p3) + 1; if (length &lt;= sizeof(str1k)) combined = str1k; else combined = malloc (length); if (combined == NULL) { printf ("Result : &lt;unknown since I couldn't get any memory&gt;\n"); } else { strcpy (combined, p1); strcat (combined, p2); strcat (combined, p3); printf ("Result : %s", combined); } if (combined != str1k) free (combined); } </code></pre> <p>which uses stack storage if the combined string will fit and only allocates memory if it won't. This can often lead to a substantial speed improvement if the bulk of strings combine into less than the limit.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload