why cant we use strcat without initialing first parameter?
e.g.
char *b = "a";
char *a;
strcat(a,b);

Dani AI

Generated

Short answer: strcat writes into its first argument, so that argument must be a valid, writable buffer that already contains a terminating NUL and has enough free space for the result. correctly noted the pointer in the original post was uninitialized; correctly pointed out the destination must be owned and writable (not a literal). Using an indeterminate pointer or trying to overwrite a literal causes undefined behavior.

A few practical options and pitfalls:

  • A fixed array with guaranteed capacity works if the remaining space is computed correctly. When using strncat, the count is the maximum number of characters to append, not the total buffer size; the usual pattern is strncat(dest, src, sizeof(dest) - strlen(dest) - 1).
  • Dynamically allocate enough space before concatenation: allocate strlen(s1) + strlen(s2) + 1 bytes, copy the first string, then append the second. Always check allocation success and free when done.
  • In C++ prefer std::string which manages capacity and avoids these manual errors.

Code examples:

char dest[32] = "start ";
char src[] = "more text";
strncat(dest, src, sizeof(dest) - strlen(dest) - 1);
size_t n = strlen(a) + strlen(b) + 1;
char *buf = malloc(n);
if (buf) {
    snprintf(buf, n, "%s%s", a, b);
    free(buf);
}

Final notes: modifying string literals is undefined; uninitialized pointers lead to undefined behavior and possible crashes. When portability and safety matter, prefer snprintf, strlcat (where available), or std::string. Reference material: strcat documentation, strncat documentation, and C++ std::string.

Recommended Answers

All 2 Replies

MSDN says about strcat:
char *strcat( char *strDestination, const char *strSource );
Parameters
strDestination
Null-terminated destination string

strSource
Null-terminated source string

In your case pointer a is unitialized and does not point to null-terminated string.

> why cant we use strcat without initialing first parameter?
Because the first parameter is the array that strcat writes to. It can't be an uninitialized pointer because you have to own the memory that the pointer points to and it can't be a pointer to a string literal because string literals are read-only.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.