function works if called once, memory leak if i call it again

EDIT: my bad the problem was not inside the function

Hello,

a few months ago i wrote here for help and some experienced users helped me with a pointer-headache i was facing while writing a function that took a char array and splitted it in a bidimensional char array (http://www.cplusplus.com/forum/general/262947/ )

Now i am writing again for the same function because I just discovered a weird behaviour: when i call once this function it works good, but if i call it again there is a memory leak which i wasn't able to identify:

this is my test program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//g++  5.4.0
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdint.h>
#define print std::cout
#define endl "\n"


char **stringSplit(char ***dest_arr, size_t *len_dest_arr, const char *str, const char *delimiters)
{
    int str_len = strlen(str) + 1; // add null terminator
    char str_copy[str_len];        // we work on a copy
    strcpy(str_copy, str);

    *dest_arr = (char **)malloc(sizeof(char*) * str_len); // over size

    uint8_t counter = 0;                        // limited to 255 sub strings
    char *token = strtok(str_copy, delimiters); // split until first delimiter
    while (token != nullptr)
    {
        (*dest_arr)[counter] = (char *)malloc(sizeof(char) * (strlen(token) + 1)); // add null terminator
        strcpy((*dest_arr)[counter], token);                      // copy token to dest_array
        print << (int)counter << ": " << token << endl;
        token = strtok(NULL, delimiters);                         // continue splitting
        counter++;
    }

    *dest_arr = (char **)realloc(*dest_arr, sizeof(char*) * counter); // reallocate the right amount of memory
    *len_dest_arr = counter;                                               // save size
    return (*dest_arr);
}



int main()
{
    char log[]= "get timelapse/M=1:T=3/end http1.1";
    
    char** token= nullptr;
    size_t token_len;
    stringSplit(&token, &token_len, log, "/ ");
    
    char data[strlen(token[2]+1)];
    strcpy(data, token[2]);
    
    for (int n=0; n<token_len;n++)
    {
        free(token[n]);
    }
    free(token);
    
    print << data << endl;
    
    char** token2 = nullptr;
    size_t token2_len;
    stringSplit(&token2, &token2_len, data, "=:");
    
    for (int n=0; n<token2_len;n++)
    {
        print << n << ": " << token2[n] << endl;
    }   
}

Last edited on
how do you know?
a leak detector will probably nail you for not freeing token2, which isn't related to the function.

I see no leak in the actual function. Its only when its used, if you do not destroy the memory that it got for you, that would leak.
Last edited on
I am very sorry i found the error, it was not in the function....
Last edited on
May I ask some help too?
Working on an answer for this thread, I jotted down the following draft:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <cstring>
#include <iostream>


namespace aster {


struct ArrOfArrs {
    int size {};
    int capacity {};
    char** arr { nullptr };

    ArrOfArrs() = default;
    ArrOfArrs(char** arr_arg, int size_arg);
    explicit ArrOfArrs(const char* const str, const char* const delim);
    ArrOfArrs(const ArrOfArrs&);
    ArrOfArrs& operator=(const ArrOfArrs&);
    ArrOfArrs(ArrOfArrs&&);
    ArrOfArrs& operator=(ArrOfArrs&&);
    ~ArrOfArrs();

    void copyArrs(const char* const * const rhs_arr);
    void addElem(const char* const rhs_arr);
    void doubleArrs();
};


ArrOfArrs::ArrOfArrs(char** arr_arg, int size_arg)
    : size { size_arg }
    , capacity { size_arg }
{
    arr = new char*[size];
    for (int i {}; i < size; ++i) {
        arr[i] = new char[std::strlen( arr_arg[i] + 1 )];
        std::strcpy( arr[i], arr_arg[i] );
    }
}


ArrOfArrs::ArrOfArrs(const char* const str, const char* const delim)
{
    // Work on copy required:
    char* mycopy { new char[std::strlen(str) + 1] };
    std::strcpy( mycopy, str );

    char* token { std::strtok(mycopy, delim) };
    while (token != nullptr) {
        addElem(token);
        token = std::strtok(nullptr, delim);
    }
    delete[] mycopy;
    delete[] token;
}


ArrOfArrs::ArrOfArrs(const ArrOfArrs& rhs)
{
    size = rhs.size;
    capacity = rhs.capacity;
    arr = new char*[size];
    copyArrs(rhs.arr);
}


ArrOfArrs& ArrOfArrs::operator=(const ArrOfArrs& rhs)
{
    size = rhs.size;
    capacity = rhs.capacity;
    arr = new char*[size];
    copyArrs(rhs.arr);

    return *this;
}


ArrOfArrs::ArrOfArrs(ArrOfArrs&& rhs)
{
    auto temp_size { size };
    auto temp_capacity { capacity };
    auto temp_arr { arr };

    size = rhs.size;
    capacity = rhs.capacity;
    arr = rhs.arr;

    rhs.size = temp_size;
    rhs.capacity = temp_capacity;
    rhs.arr = temp_arr;
}


ArrOfArrs& ArrOfArrs::operator=(ArrOfArrs&& rhs)
{
    auto temp_size { size };
    auto temp_capacity { capacity };
    auto temp_arr { arr };

    size = rhs.size;
    capacity = rhs.capacity;
    arr = rhs.arr;

    rhs.size = temp_size;
    rhs.capacity = temp_capacity;
    rhs.arr = temp_arr;

    return *this;
}


ArrOfArrs::~ArrOfArrs()
{
    std::cout << "- - -\nDeleting...\nsize: " << size
              << "; capacity: " << capacity << '\n';
    for (int i {}; i < size; ++i) {
        std::cout << i << ") deleting '" << arr[i]
                  << "' of size " << std::strlen(arr[i])
                  << "...";
        delete[] arr[i];
        std::cout << " deleted\n";
    }
    delete[] arr;
}


void ArrOfArrs::copyArrs(const char* const * const rhs_arr)
{
    for (int i {}; i < size; ++i) {
        arr[i] = new char[std::strlen( rhs_arr[i] + 1 )];
        std::strcpy( arr[i], rhs_arr[i] );
    }
}


void ArrOfArrs::addElem(const char* const rhs_arr)
{
    if (capacity <= size) {
        doubleArrs();
    }
    arr[size] = new char[std::strlen(rhs_arr) + 1];
    std::strcpy( arr[size], rhs_arr );
    std::cout << "Adding element '" << arr[size] << "' at position " << size
              << "; capacity is " << capacity
              << " <---\n";
    ++size;
}


void ArrOfArrs::doubleArrs()
{
    if (size == 0) {
        capacity = 1;
        arr = new char*[capacity];
        return;
    }

    char** temp { new char*[capacity * 2] };
    for(int i {}; i < size; ++i) {
        temp[i] = new char[std::strlen( arr[i] + 1 )];
        std::strcpy( temp[i], arr[i] );
    }
    for(int i {}; i < size; ++i) {
        delete[] arr[i];
    }
    delete[] arr;
    arr = temp;
    capacity *= 2;
}


}


int main()
{
    const char* log { "get timelapse/M=1:T=3/end http1.1" };
    aster::ArrOfArrs tokens_1(log, "/ ");

    std::cout << "tokens_1:\n";
    for (int n {}; n < tokens_1.size; ++n) {
        std::cout << "- " << tokens_1.arr[n] << '\n';
    }

    aster::ArrOfArrs tokens_2(log, "/ ");
    std::cout << "\ntokens_2:\n";
    for (int n {}; n < tokens_2.size; ++n) {
        std::cout << "* " << tokens_2.arr[n] << '\n';
    }
}


There’re probably hundreds of issus, but my first problem is it breaks when cleaning the memory (I’ve added verbose couts to emphasize it).
The funniest thing is it runs fine if I make this changes:
from:
1
2
3
4
const char* log { "get timelapse/M=1:T=3/end http1.1" };
aster::ArrOfArrs tokens_1(log, "/ ");
...
aster::ArrOfArrs tokens_2(log, "/ ");

to:
1
2
3
4
const char* log { "get timelapse-M=1:T=3-end http1.1" };
aster::ArrOfArrs tokens_1(log, "- ");
...
aster::ArrOfArrs tokens_2(log, "- ");

(i.e. turn the ‘/’ into ‘-’)

And it runs fine on Wandbox (which is likely to be a Linux machine).

This is the output on my W7 machine:
Adding element 'get' at position 0; capacity is 1 <---
Adding element 'timelapse' at position 1; capacity is 2 <---
Adding element 'M=1:T=3' at position 2; capacity is 4 <---
Adding element 'end' at position 3; capacity is 4 <---
Adding element 'http1.1' at position 4; capacity is 8 <---
tokens_1:
- get
- timelapse
- M=1:T=3
- end
- http1.1
Adding element 'get' at position 0; capacity is 1 <---
Adding element 'timelapse' at position 1; capacity is 2 <---
Adding element 'M=1:T=3' at position 2; capacity is 4 <---
Adding element 'end' at position 3; capacity is 4 <---
Adding element 'http1.1' at position 4; capacity is 8 <---

tokens_2:
* get
* timelapse
* M=1:T=3
* end
* http1.1
- - -
Deleting...
size: 5; capacity: 8
0) deleting 'get' of size 3... deleted
1) deleting 'timelapse' of size 9... deleted
2) deleting 'M=1:T=3' of size 7...
and breaks.
What exactly do you mean by "and breaks"?

If you get some kind of error message, post it exactly as it appears in your development environment.

If the program is crashing, run it with your debugger, then examine the values of the variables at the time of the crash.

Last edited on
Well, ok, I feel embarrassed for this.
This line in ArrOfArrs::doubleArrs():
temp[i] = new char[std::strlen( arr[i] + 1 )];
must become:
temp[i] = new char[std::strlen( arr[i] ) + 1];

jlb wrote:
If the program is crashing

Oh, right! Not ‘breaks’ but ‘crashes’. Sorry for my poor English.

- - -
I promise I’ll (try to) cut down on hijacking!
Topic archived. No new replies allowed.