Skip to main content

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.

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_trds_vector_new()
{
        
rds_vector_tnew_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_tvecvoidobj)
{
        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_tvec)
{
        
size_t na vec->numalloci;
 
        for(
i=0i<na; ++i)
        
                
free(vec->objs[i]);
 
        
free(vec->objs);
}
 
/**** main.c ****/
#include "rds_vector.h"
 
int main(int argcchar** argv)
{
        
rds_vector_tvec rds_vector_new();
 
        
chararr0"hello0";
        
        
rds_vector_add(vecarr0);
 
        
rds_vector_free(vec);
 
        return 
exit_success;

have day!

compile code using -g flag , use gdb step through code.
do:
code:
 gdb your_program break your_function, or file:line run
it tell when , segfault occurs.

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

Popular posts from this blog

How to change text Component easybook reloaded *newbee* - Joomla! Forum - community, help and support

After Effect warning: A problem occurred when processing OpenGL commands

Preconditions Failed. - Joomla! Forum - community, help and support