Yeah this is a simple question and pretty popular. And this is what I did.
There is a segmentation fault when we copy characters from src into dest . Now, I can understand the source of this fault - when we iterate over the dest string we reach the end and then the dest pointer points to the 'string terminator' or 0. So next when we put *dest++=*src++ it obviously will give an error.

//includes
void concat(char * dest, const char * src) {    
      while (*dest) ++dest;    
      while (*dest++ = *src++);     
 }

void main(){
	concat("hi","hello");
	getch();
}

The only way to beat this is to preallocate memory equal to the sum of both the strings - but that kind of beats the purpose of this method. And secondly I have searched online and found similar codes.

What am I missing?

Recommended Answers

All 2 Replies

my bad. it seems even the inbuilt strcat fails and the simple reason is not enough space in the destination string.
one way to get past this is to declare a long string array and have a char pointer point to it. you can send this pointer to strcat as the first pointer.

but still i am not satisfied-there must be some other alternative!

Yeah this is a simple question and pretty popular. And this is what I did.
There is a segmentation fault when we copy characters from src into dest . Now, I can understand the source of this fault - when we iterate over the dest string we reach the end and then the dest pointer points to the 'string terminator' or 0. So next when we put *dest++=*src++ it obviously will give an error.

//includes
void concat(char * dest, const char * src) {    
      while (*dest) ++dest;    
      while (*dest++ = *src++);     
 }

void main(){
	concat("hi","hello");
	getch();
}

The only way to beat this is to preallocate memory equal to the sum of both the strings - but that kind of beats the purpose of this method. And secondly I have searched online and found similar codes.

What am I missing?

You can't concantinate one string literal to another string literal because both string literals are normally (but not always) placed in read-only memory. What you have to do is below. Your concat() function should work ok as you wrote it.

int main()
{
   char s1[255] = "Hello ";
   concat(s1,"World");
}

>>there must be some other alternative!
There is -- see strcat_s(), but that is not a standard C function.

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.