I have a function `vector_push` that pushes data to a vector like this:
void vector_push(vector *v, void *item)
{
if (v->capacity == v->size)
vector_resize(v, v->capacity * 2);
v->data[v->size++] = item;
}
It's a pretty standard vector_push
function in c
. Now, I am trying to transfer some data into it using this function:
int transfer(char temp[100], vector *v) {
vector_push(v, strdup(&temp[0]));
memset(temp, 0, 100);
return 0;
}
The problem is, strdup
leaks. So, I instead wrote this:
int transfer(char temp[], vector *v) {
char *d = malloc(strlen(&temp[0]) + 1);
strcpy(d, &temp[0]);
vector_push(v, d);
memset(temp, 0, 100);
return 0;
}
This is pretty much the strdup
function.
Some explanation first. temp
accrues some values that I want to push to my vector at some point. After I push, I need to reset temp and start accruing data into it once more from where I left off. However, when I memset
temp, the data I pushed into my vector was lost. Obviously. So I used strdup
, but then I got memory leaks.
So I decided to expand strdup
and free the char* it was returning. But of course this just puts me in the same situation as last time.
I'm just not sure how to push my data to the vector then reset "temp" without leaking and without losing the data in vector. How should I do it?
Edit:
Valgrind output:
==16158== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16158== by 0x4ED99B9: strdup (strdup.c:42)
==16158== by 0x1099A6: transfer (tokens.c:20)
==16158== by 0x109AF2: tokenize (tokens.c:35)
==16158== by 0x109848: main (nush.c:246)
==16158==
==16158== LEAK SUMMARY:
==16158== definitely lost: 17 bytes in 3 blocks
==16158== indirectly lost: 0 bytes in 0 blocks
==16158== possibly lost: 0 bytes in 0 blocks
==16158== still reachable: 0 bytes in 0 blocks
==16158== suppressed: 0 bytes in 0 blocks
==16158==
==16158== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==16158== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)