×

# strcat() in c and append in c++

 0 I declared char s[100] as a character array and then in the later part of the program i took s as an input string and then used strcat(s,s) ,then it showed "Runtime Error" But when in c++ , i declared s as a string and used s.append(s), then it worked correctly and both these functions perform the same function , so why is there an error in c but not in c++?? asked 11 Apr '15, 13:19 41●1●4 accept rate: 50% 1★arun_as 741●3●6●18

 0 Note, I will be reffering to character arrays as strings. strcat() will overwrite everything ( starting from the null character in the first string ) in the first string until the null character '\0' in the second string is reached. But, when you pass the same string as both the parameters, then it will start overwriting the first string and overwrites the null character, and at the same time, the second string obtains the same changes. So, the null character wil be overwritten and there will be nothing left to stop the execution of strcat(). Let us look at it. This is a string s t r i n g \0 ^ ^ st en  st is the start and en is the position to be overwritten. Now let us look how strcat() works s t r i n g s ^ ^ st en s t r i n g s t ^ ^ st en s t r i n g s t r ^ ^ st en s t r i n g s t r i ^ ^ st en s t r i n g s t r i n ^ ^ st en s t r i n g s t r i n g ^ ^ st en s t r i n g s t r i n g s ^ ^ st en  As you can see, it will keep on appending the string without an end as there is no longer a null character. Since there is no null character to tell the function to stop, it just keeps on appending it. .So, once the string exceeds the length you specified, it will try to access unsafe memory which should not be accessed and you will get a SEGMENTATION FAULT. This is what is causing the problem. But this is not how append() in c++ works. So you don't get an error there. answered 11 Apr '15, 18:04 1★arun_as 741●3●6●18 accept rate: 10% thanx a lot! cheers (11 Apr '15, 18:36)
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,917
×1,490
×643

question asked: 11 Apr '15, 13:19

question was seen: 4,628 times

last updated: 11 Apr '15, 18:45