Thread: Help freeing allocated memory.
it has been long time since wrote in c, , i'm trying build vector.
wrote constructor , 'add' method.
want test , free allocated memory after using vector, keep getting segfault.
guess 'free' method wrong need game of pointers.
in advance.
have day!php code:/**** the vector type ****/
typedef struct _rds_vector_t
{
void** objs; // the vector
size_t size; // the size of the vector
size_t numalloc; // number of allocated objects.
} rds_vector_t;
/**** the constructor ****/
rds_vector_t* rds_vector_new()
{
rds_vector_t* new_vec;
if((new_vec = (rds_vector_t*)malloc(sizeof(rds_vector_t))) == null)
rds_vector_failure(__line__, "malloc failed.");
new_vec->objs = null;
new_vec->size = new_vec->numalloc = 0;
return new_vec;
}
/**** add method ****/
void rds_vector_add(rds_vector_t* vec, void* obj)
{
if(!vec->size)
{
if((vec->objs = (void**)malloc(sizeof(void*))) == null)
rds_vector_failure(__line__, "malloc failed.");
vec->objs[0] = obj;
vec->size = vec->numalloc = 1;
return;
}
if (vec->size == vec->numalloc)
rds_vector_amortization(vec);
vec->objs[vec->numalloc++] = obj;
return;
}
/**** free method ****/
void rds_vector_free(rds_vector_t* vec)
{
size_t na = vec->numalloc, i;
for(i=0; i<na; ++i)
free(vec->objs[i]);
free(vec->objs);
}
/**** main.c ****/
#include "rds_vector.h"
int main(int argc, char** argv)
{
rds_vector_t* vec = rds_vector_new();
char* arr0= "hello0";
rds_vector_add(vec, arr0);
rds_vector_free(vec);
return exit_success;
}
compile code using -g flag , use gdb step through code.
do:
it tell when , segfault occurs.code:gdb your_program break your_function, or file:line run
should check tutorial gdb, useful tool. gets rid of lot of headaches in cases one.
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk [SOLVED] Help freeing allocated memory.
Ubuntu
Comments
Post a Comment