1

I am pretty new to C programming, and trying to run a simple program, which put string t at the end of string s:

#include <stdio.h>

void _strcat(char *s, char *t){
    for(;*s;s++);
    for(;(*s=*t)!='\0';s++,t++);

}

int main()
{
    char *s="hello";
    char *t="how are you?";

    _strcat(s,t);

    getchar();
    return 0;
}

But I constantly get an annoying error for assigning two pointers (of the same type) *s=*t; this is the error:

Thread 1: EXC_BAD_ACCESS (Code 2, Address=.....)

Shahb
  • 47
  • 1
  • 6
  • Unrelated to your problem, but you should not use global names with leading underscore, those are reserved by the C specification. – Some programmer dude Sep 03 '13 at 05:47
  • 1. It's called "Xcode", not "XCODE". 2. But this has nothing to do with Xcode anyway. 3. This is a dupe. 4. I don't see a question. 5. Identifiers starting with an underscore are reserved to the implementation. If you name your function `_strcat`, then your program invokes undefined behavior. –  Sep 03 '13 at 05:47

1 Answers1

7

String literals are read only, so trying to modify one is undefined behavior. Not only that but they are only the exact size of the string (plus one for the terminator) so the first string will not fit the second being appended so you will overwrite some memory leading to even more undefined behavior.

the string you want to append to should be declared as an array, one that is big enough to fit both strings. Like for example:

char s[128] = "hello";

How to use only pointer and allocate on the heap:

char *s = malloc(128);
strcpy(s, "hello");

Don't forget to free the allocated memory after use.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks Joachim, you helped a lot. But I wanted to write this with pointers, do you have any idea how to write it with pointers not arrays ? – Shahb Sep 03 '13 at 14:44
  • @Shahb Then allocate memory on the heap with e.g. `malloc`. See my updated answer for an example. – Some programmer dude Sep 03 '13 at 14:49