Today I was met the following code block:
#include <iostream>
using namespace std;
char *return_char_array(const char *cptr)
{
char charArray[100] = {0};
strcpy(charArray, cptr);
return charArray;
}
int main()
{
const char *cptr = "test";
char localCharArray[100] = {0};
strcpy(localCharArray, return_char_array(cptr)); // output "test"
cout<<localCharArray<<endl;
string s = return_char_array(cptr); // corrupt output
cout<<s<<endl;
return 0;
}
At the first sight I thought both the output would be corrupt but surprisingly the first output is “test” while the second is corrupt. Would someone tell me why?
They are both corrupt. Just because it appears to work, doesn’t mean it’s ok.
This is undefined behavior, anything can happen, including appearing to work.