Realloc, malloc
Why there is memory leak when I use realloc, malloc alot and that sure those res going to be freed?
I noticed it happens too with std::vector, deque etc containers
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
|
#include<stdio.h>
#include<windows.h>
/**************************************************************************************************/
#include<stddef.h>
#include<stdlib.h>
static const size_t VOID_SIZE=sizeof(void*);
typedef struct{
void**list;
size_t len;
size_t cap;
}voids;
voids*voidsnew(size_t cap){
voids*cont=(voids*)malloc(sizeof(voids));
cont->len=0;
cont->cap=cap;
cont->list=(void**)malloc(VOID_SIZE*cap);
return cont;
};
void voidsclose(voids*cont){
free(cont->list);
free(cont);
};
void voidspush(voids*cont,void*item){
if(cont->len==cont->cap){
cont->cap+=cont->cap;
cont->list=realloc(cont->list,VOID_SIZE*cont->cap);
};
cont->list[cont->len]=item;
++cont->len;
};
void voidspop(voids*cont){
--cont->len;
cont->list[cont->len]=NULL;
};
/**************************************************************************************************/
int main(){
size_t pos=0;
size_t len=10000000;
//voids*ar=voidsnew(len);//with this memory will be around 300-400 kB after free-ing
voids*ar=voidsnew(4); //with this memory will be around 800-900 kB after free-ing
for(;pos<len;++pos){
voidspush(ar,(void*)pos);
};
Sleep(2000);
voidsclose(ar);
getchar();
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.