Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

Eliminating Memory Leak in C++

I have created a function named substring and used it in the following way:-

char* substring(char* source, int startIndex, int endIndex)
{
    int size = endIndex - startIndex + 1;
    char* s = new char[size+1];
    strncpy(s, source + startIndex, size);
    s[size]  = '\0';
    return s;
}

char *game1 = new char[10]
char* a0 = substring(csv, 0, x[0]);
game1 = a0;
//delete[] a0;
delete[] game1;

But, it is causing some memory leak after checking it through Valgrind. When I delete a0, the program doesn't work. How can I deal with this problem? Thanks.

I have made an edit:-

char* game1 = substring(csv, 0, x[0]);
delete[] game1;

Upvotes: 2

Views: 105

Answers (1)

user11747064
user11747064

Reputation:

The problem is near char *game1 = new char[10] You have assigned char[10] to game1 which you never deleted.

Try by adding delete[] game1;

before

game1 = a0;

Actually you don't need to assign that char[10] to game1 I don't know why you have done it. Removing that may also work. Just declaring as

char *game1; 

Upvotes: 3

Related Questions