I have tried troubleshooting this problem and just ended up with nothing, I hope you can hint me in the right direction. I have a program where I initialized a char array this way :
char variable1[8];
And then I try to copy a return value of a function i.e
...
strcpy(variable1, (char *)function1());
Where function1() returns char array value.
Here is the structure of function1 :
char* function1()
{
....
char variable2[8]={'\0'};
...
return (variable2);
}
The program crashes when I try to execute the strcpy line.
I have read on strcpy function here that
Important: You must ensure that the destination buffer (s1) is able to contain all the characters in the source array, including the terminating null byte. Otherwise, strcpy() will overwrite memory past the end of the buffer, causing a buffer overflow, which can cause the program to crash
Therefore I tried to increase variable1 size to 20, but still the program crashes.
Aside from that, I tried different approach i.e use strncpy function call, and it is still giving me the same error.
The strange thing is that I could execute function1() which returns a value without a problem. Only when I tried to copy it over, my program crashes. Any ideas what I should do next?
Your problem is not because your destination buffer is too small, it’s because the variable containing the source string has gone out of scope before you try to use it.
Within
function1,variable2is created on the stack but this is effectively destroyed when you exit the function. Trying to use it afterwards (such as in astrcpyoperation) is undefined behaviour.If you want an array that will survive function exit, you probably want to allocate it from the heap:
and remember to free the pointer afterwards.