0

In this part of my code (receiving the time) I have a dynamically sized array of chars. This is for a school project and dynamically sized arrays are required.

char* msgtime::getTime() {

    std::string t;
    t.append(std::to_string(hour));
    t.append(":");
    t.append(std::to_string(minute));

    char *charTime = new char[t.length()];
    strcpy(charTime, t.c_str());

    return charTime;
}

However, I can't delete the charTime since I am returning the value. I tried following another question I saw on here to return it into a char* in the main program then delete that when I'm done with it. The code here is what the function is returning to:

void receive(packet &data, SOCKET con) {
    msgtime tim;

    cout << "Receiving data" << endl;
    int in = recv(con, (char*)&data, sizeof(data), 0);
    cout << "Data received: " << in << endl;

    tim.updateTime();
    char *newTime = tim.getTime();
    strcpy(data.time, newTime);
    delete[] newTime;

}

Except when I run it I get this error:

HEAP CORRUPTION DETECTED: after Normal block (#183) at 0x00129330 CRT detected that the application wrote to memory after the end of heap buffer.

I need to delete the charTime in the getTime function to plug the memory leak but I can't figure out how to do it. Any help is GREATLY appreciated!

8
  • 4
    "This is for a school project and dynamically sized arrays are required." Your teacher may or may not know that, but the standard runtime-sized array in C++ is std::vector. Please avoid all operator new[] business. Commented Jun 16, 2017 at 21:12
  • Please, please, please just use smart pointers and/or standard container classes instead of manual memory management and keep your sanity.. Commented Jun 16, 2017 at 21:13
  • @BaummitAugen vectors aren't covered in the curriculum for this class Commented Jun 16, 2017 at 21:13
  • 2
    @BryceThompson You may want to consider supplementing your class with a good C++ book then, so you don't end up learning 90s C++ in 2017. Commented Jun 16, 2017 at 21:17
  • 1
    use std::string and if someone asks where the dynamically sized array is, then show them std::string::data() Commented Jun 16, 2017 at 21:19

1 Answer 1

1

You don't allocate enough space, one more char is required to store null terminator:

char *charTime = new char[t.length() + 1];
Sign up to request clarification or add additional context in comments.

2 Comments

That said, why don't you just return std::string directly?
yep, that did it. stupid mistake on my part but im so glad it works now! i ran visual leak detector and now it works fine, thanks a bunch :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.