Can I make a call to make a new instance fail safely

Aug 20, 2012 at 4:38pm

Can I make a call to make a new instance fail safely

I am creating an object with large variable t_atom arrays as storage for attributes.

In order to allocate memory for the storage I am calling a memory allocator in the new routine. Assuming this fails, what is a safe way to prevent my object from being created, as I have no way of telling max that the attributes should not be accessed?
The attributes have a custom setter in case it is relevant.

I assume returning a null pointer in new might work, but should I clean-up the object allocation first?

Alex

#64040
Aug 20, 2012 at 5:22pm

Hi,

Learning C long time ago i asked something more or less about that : http://cycling74.com/forums/topic.php?id=23093

Now, i do that :

void *zoulou_new(t_symbol *s, long argc, t_atom *argv)
{
    t_zoulou *x = NULL;

    if (x = (t_zoulou *)object_alloc(zoulou_class)) {
    //
    x->values = (long *)sysmem_newptr(sizeof(long) * MAXIMUM_SIZE_LIST);
    x->factorOracle = pizFactorOracleNew(0, NULL);

    if (x->values && x->factorOracle) {

        x->straightRatio     = DEFAULT_STRAIGHT;
        x->backwardThreshold = DEFAULT_BACKWARD;

        x->rightOutlet = outlet_new(x, NULL);
        object_obex_store((void *)x, zoulou_sym_dumpout, (t_object *)x->rightOutlet);
        x->leftOutlet = listout((t_object *)x);

        systhread_mutex_new(&x->algorithmMutex, SYSTHREAD_MUTEX_NORMAL);

        attr_args_process(x, argc, argv);

    } else {
        object_free(x);
        x = NULL;
    }
    //
    }

    return x;
}

void zoulou_free(t_zoulou *x)
{
    if (x->values) {
        sysmem_freeptr(x->values);
    }

    pizFactorOracleFree(x->factorOracle);

    if (x->algorithmMutex) {
        systhread_mutex_free(x->algorithmMutex);
    }
}

HTH

#230982
Aug 24, 2012 at 8:15pm

Hi Alex,

Yes, you should return NULL from your new method. This is what we do where appropriate. And, yes, you should also clean-up anything you’ve alloc’d from the heap in the process.

Cheers,
Tim

#230983

You must be logged in to reply to this topic.