| |

VerySource

 Forgot password?
 Register
Search
View: 697|Reply: 2

▲ When should the memory be released?

[Copy link]

1

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2019-12-27 17:34:20
| Show all posts |Read mode
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

typedef struct
{
        int keyLen;
        char * recordKey;
} keyElement;

void allc (vector <keyElement>&idx)
{
        string names [] = {"jack", "mike"};

        for (int i = 0; i <2; i ++)
        {
                keyElement tmp;
                tmp.keyLen = names [i] .length ();
                tmp.recordKey = new char [tmp.keyLen];
                strcpy (tmp.recordKey, (const char *) names [i] .c_str ());
                idx.push_back (tmp);
                // delete [] tmp.recordKey; // delete here will cause an error: the data in index cannot be accessed in main
        }
}


int main ()
{
        vector <keyElement> index;

        allc (index);
        cout << index [0] .recordKey << "" << index [1] .recordKey << endl;
        cout << index.size () << endl;

// delete [] index [0] .recordKey; // Why is it wrong to delete here?
// delete [] index [1] .recordKey;
        return 0;
}
Reply

Use magic Report

0

Threads

22

Posts

18.00

Credits

Newbie

Rank: 1

Credits
18.00

 China

Post time: 2020-1-3 10:30:02
| Show all posts
tmp.recordKey = new char [tmp.keyLen];
Change to tmp.recordKey = new char [tmp.keyLen + 1]; try

string.length () did not calculate '\0', and strcpy copied '\0'
recordKey length exceeds the memory of new char [], delete [] fails
Reply

Use magic Report

0

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-1-3 14:27:01
| Show all posts
I also think it makes sense
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list