Problem the Strings in C++
Hi guys,
i wrote one simple program in C++ as follows, #include<iostream.h> #include<string.h> main() { char *temp="How are you"; char *ret=""; strcpy(ret,temp); cout<<temp; } It is running in windows fine. But with linux, it gives "Segmentation Fault (core dumped)" Error. But it compiles with no error. If i change the destination variable in strcpy to fixed array size like char ret[100]; it works fine in linux. why linux is not accepting the destination as pointer char. thanx in advance Jagadish |
The question should be, "Why is Windows accepting running this buggy code ?"
No surprise so many viruses are happy in the Windows ecosystem ! |
Hi,
Can u explain me what is wrong with that code. Can't we use the char pointer as destination in strcpy. thanx for ur reply Jagadish |
The problem is that the character array at "ret" is not large enough (only 1 char) to hold the null-terminated string "How are you" (12 chars) and you're writing past the end of the array into other parts of memory.
|
You can use a char pointer as destination, but it need to point to some memory you are allowed to write to and with sufficient storage.
This pointer is initialized in your code to a one byte array that may or may not be writable, depending of the compiler implementation/options, the strcpy is also trashing some part of your windows stack as you are overwriting whatever is after this one byte array with the remaining of your source string. |
All times are GMT -5. The time now is 04:28 AM. |