We are given:
typedef const char* V;
typedef std::vector<V> Record;
We instantiate the record somewhere in code like:
Record rec;
We populate it with data via malloc:
void fixed_len_read(void *buf, int size, Record *record){
char *c_buf = (char *)malloc(size);
memcpy(c_buf, buf, size);
record->push_back(c_buf);
}
Now after usage, I wish to free the memory allocated. Would it go away on it's own? Or would I have to free() every element? I tried to call free like this:
for (int i =0; i < 100; i++) {
free(record.at(i));
}
But it complains about const char.
" error: no matching function for call to 'free'
free(record.at(i));"
I then used a cast:
for (int i =0; i < 100; i++) {
free((char *) record.at(i));
}
Now it seems to run, but I'm not sure if it works? Does that look right?
[EDIT]
As per comments and answer below. Casting it is ok. An alternative is to use delete() as per:
Unable to free const pointers in C
(C's free has an issue, which was fixed in delete() in c++).