During one of my recent interviews, I was asked to implement and test a user defined version of memcpy() function in C++.
My code was something like this:
#include <iostream>
void my_memcpy(void* src, void* dest, size_t size)
{
char* m_src = (char*)src;
char* m_dest = (char*) dest;
for (int i=0; i<size ; i++)
*(m_dest+i) = *(m_src+i);
}
int main()
{
char* source;
char* destination;
source = new char[20];
destination = new char[20];
source = "Hello";
my_memcpy(source, destination,5);
std::cout << destination << "
";
delete[] source;
delete[] destination;
return 0;
}
The program would run with a warning, but output correctly and then crash at the end. Output
When I commented out the delete[] source line, the program wasn't crashing anymore. I still don't understand why delete[] source would lead to a crash.
Kindly help me in explaining this or guide me to some reference which can clarify the underlying concept.
question from:https://stackoverflow.com/questions/66057982/program-crashed-while-trying-to-delete-a-dynamically-allocated-array