strcat() error with gcc
Hi friends
I have one particular problem with this following short code written in C #include<stdio.h> #include<string.h> int main() { printf("%s",strcat("Hello","World"); return 0; } I m getting the error as segmentation fault. If I run the same code in Tourbo C or Borland C, it works fine. Please help me what is the problem with this code or where i have gone wrong. |
maybe it is this parethesis:
printf("%s",strcat("Hello","World")); anyway thats asyntax error... |
yeh.. sorry
it was typing mistake.. I am getting segmentation fault |
The erronious program is as follows
#include<stdio.h> #include<string.h> int main() { printf("%s",strcat("Hello","World")); return 0; } giving segmentation fault |
Does it work if you explicitly 0-terminate the strings? ( printf("%s",strcat("Hello\0","World\0")); )
|
No ..
Still it is giving the same error. The thing is that the above code works properly under Turbo and Borland compilers |
Ah, silly me, should have RTFM before answering. Of course it's
char *strcat( char *strDestination, const char *strSource ), therefore you're writing the result into the memory reserved for "Hello". The code should rather look like #define PLENTY_OF_BYTES 32 char szresult[PLENTY_OF_BYTES]; szresult[0]=0; strcat(szresult,"Hello"); strcat(szresult," World"); |
hi
that I can understand.. but why the same code works in borland compiler and tourbo compiler why not in gcc ..!!!!! Any clue abt this ? |
Because gcc stores string literals in read-only memory. The same program will probably work if you compile it with gcc -fwritable-strings prog.c -o prog althought you'll have undefined results.
|
thanks..atlease we able to remove the segmentation fault.
yes.. it is not giving error like segmentation fault. But it is giving only the part of the appended string. In the above example code it gives the output orld It means , it is missing the first character of second (source)string and not showing first string i.e destination . You can try in your PC also...! Why it is like this? Can anybody guide me ? |
Because the only correct way to use strcat() is the way Marius2 showed you.
|
gcc is correct, string literals are null-terminated and of type
Code:
const char* |
Ohh god that code makes my brain cry
using strcat like this should be banned :P |
Hi friends
there is a food for thought...! To my knowledge, strcat("Hello","World"); returning the pointer to string..am i right ? For example, the below code works properly where p is the pointer to string. int main() { char *p="Suresh"; printf("%s",p); return 0; } why not in the first code or what is the difference between two approach. awaiting your reply. |
Here's a way to code your own strcat() function:
Code:
char *mystrcat(char *s1, char *s2) Here's a sample program that uses mystrcat() and will work the exact same way with C's strcat(): Code:
#include <stdio.h> Code:
itsme@dreams:~/C$ ./mystrcat |
All times are GMT -5. The time now is 01:06 PM. |