Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c++ - Program crashed while trying to delete[] a dynamically allocated array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The program crashes because you aren't delete[]'ing the pointer you allocated with new[].

char* source;
source = new char[20];
source = "Hello";
delete[] source;

You first assign source to a dynamic array of 20 chars, but then you change source to point at a string literal. A string literal isn't allocated with new[], so delete[]'ing it crashes the program.

I suppose that when you wrote source = "Hello"; what you were trying to do was copy the characters of "Hello" into the location pointed at by source, but that's not what that line of code actually does. It copies the pointer, not what is being pointed at.

Here's one way of correcting the code:

strcpy(source, "Hello");

This would also work:

memcpy(source, "Hello", 5+1); // +1 for null terminator

Both of these functions copy the characters, not the pointer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...