jeudi 8 juin 2017

Array by value multiplication memory leak in c++

I'm having some trouble with multiplying an array (char array in this particular case) by a value. My code looks like this:

char* tab1 = copy("11");
char* t2 = copy("11");
char t = '2';
int length = strlen(tab1) + 2;
char*result = populate('0', length);
int p_length = strlen(tab1);
for (int j = p_length - 1; j >= 0; j--) {
    char* tmp = multiply_chars(tab1[j], t);
    v_shove(tmp, j);
    char* tmp2 = add_tables(result, tmp);
    delete[] result;
    result = tmp2;
    delete[] tmp;
}
cout << result << endl;
delete[] result;
delete[] tab1;
delete[] t2;

None of the methods used (that's populate, multiply_chars and add_tables) seem to cause leaks when ran in an infinite loop. I've narrowed the leak to the

char* tmp2 = add_tables(result, tmp);
delete[] result;
result = tmp2;

part, but have no idea why it would happen. I check for leaks by running snippets in an infinite loop and checking memory usage. Any help would be appreciated! If need be I'll post the code of the methods used, but decided not to for the sake of brevity here. They all return new cstrings. Also, the t2 variable is there from when I was checking the array by array multiplication, which also leaked - decided to do array by value multiplication first. (Now, to be completely honest this is one of the methods required for a school project, but it's such a miniscule part of it, that I thought it wouldn't hurt if I asked - the teacher isn't really big on helping with particular code problems)

Aucun commentaire:

Enregistrer un commentaire