neilli1992
neilli1992

Reputation: 15

Bus error in my own strcat using pointer

I'm doing a pointer version of the strcat function, and this is my code:

void strcat(char *s, char *t);

int main(void) {
   char *s = "Hello ";
   char *t = "world\n";

   strcat(s, t);

   return 0;
}

void strcat(char *s, char *t) {
  while (*s)
    s++;

  while ((*s++ = *t++))
    ;
}

This seems straightforward enough, but it gives bus error when running on my Mac OS 10.10.3. I can't see why...

Upvotes: 1

Views: 454

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

In your code

char *s = "Hello ";

s points to a string literal which resides in read-only memory location. So, the problem is twofold

  1. Trying to alter the content of the string literal invokes undefined behaviour.

  2. (almost ignoring point 1) The destination pointer does not have enough memory to hold the concatinated final result. Memory overrun. Again undefined behaviour.

You should use an array (which resides in read-write memory) with sufficient length to hold the resulting (final) string instead (no memory overrun).

Suggestion: Don't use the same name for user-defined functions as that of the library functions. use some other name, e.g., my_strcat().

Pseudocode:

  #define MAXVAL 512
  char s[MAXVAL] = "Hello";
  char *t = "world\n";    //are you sure you want the \n at the end?

and then

  my_strcat(s, t);

Upvotes: 5

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

you are adding the text of 't' after the last addres s is pointing to

char *s = "Hello ";
char *t = "world\n";

but writing after 's' is undefined behavior because the compiler might put that text in constant memory, in your case it crashes so it actually does.

you should reserve enough memory where s points to by either using malloc or declare it array style

char s[32] = "Hello ";

Upvotes: 1

Related Questions