0
char* StrCat(char* dest, char* source)
{
    char* retVal = dest;

    while(*dest)
        dest++;

    while(*dest++ = *source++) ;

    return retVal;
}

int main()
{
    char* a = "One";
    char* b = "Two";

    char* x = StrCat(a, b);

    printf("%s\n", x);

    return 0;
}

The program crashes the first time when copying from source to destination, second while loop. (Access violation error)

Adrian
  • 19,440
  • 34
  • 112
  • 219

1 Answers1

2

Content of variables a and b (character strings "One" and "Two") are stored in read-only segments, content is protected, you cannot overwrite its data.

Plus, StrCat() function has not much logic.

You'd need to use a global char array, or a char array that you pass to the function that has a limited size and make sure you don't go beyond its buffer size during the copy, otherwise you will end up with a stack overflow.

Another solution would be to allocate memory dynamically using malloc, this memory should be freed when you don't need it anymore.

Rethink how you would write such a function to correct it, but first fix this memory issue.

superjedi
  • 524
  • 3
  • 7