Originally Posted by
dwks
That won't do what you think it does. It just makes outstr point to the string literal "". You probably want outstr[0] = 0; instead.
I'm not entirely sure what your question is, but I think I can answer it in a roundabout way. Memory allocation is expensive. Usually, when you're maintaining a vector or a dynamic array or anything similar (like a queue) that uses realloc(), you maintain two sizes: one is how much space you have allocated, and the other is how much space you're using out of that allocated space. Typically you'll allocate a small amount of space to start with, and when you run out, you'll double the size of the array. (When shrinking, you'll halve the size of the array when it becomes less than one-quarter full.) It can be proven that the amortized time of such an algorithm is constant.
Anyway, you probably don't need to worry about this, because in popping you're shifting every element over and throwing performance out the window anyway.
I'm not sure what your pop() is trying to do. You can't free some blocks of memory from the beginning of the list. You'd have to shift every element down one, and then free the memory for the last element.
But then i always have allocated space that stays unused, right?
I just tried another approach now:
Code:
int i=0;
strcpy(outstr, (*list)[0]);
for(i=1; i<curlen;i++){
realloc((*list)[i-1],strlen((*list)[i])+1);
strcpy((*list)[i-1],(*list)[i]);
}
free((*list)[curlen-1]);
if (curlen==0);
free((*list));
But i'm still running into seg faults...
so now anyhow, if i did try your version,i started with int alloc=2 an then when
Code:
if (curlen==alloc) {
realloc((*list),(alloc*2)*sizeof(*list));
(*list)[curlen]=malloc (strlen(str)+1);
strcpy((*list)[curlen],str);
return ++curlen;
} else {
(*list)[curlen]=malloc (strlen(str)+1);
strcpy((*list)[curlen],str);
return ++curlen;
}