Question Details

No question body available.

Tags

c pointers struct valgrind free

Answers (1)

July 8, 2026 Score: 4 Rep: 791,223 Quality: Medium Completeness: 80%

The Fundamental theorem of software engineering:

Any problem in computer science can be solved with another level of indirection.

Instead of having stack.ops point directly to the array, have it point to an intermediate pointer that both stacks share. Then when you free the array, you can set this to NULL and avoid freeing again when you free the other stack.

typedef struct sstack
{
    tnode      head;
    t_node      tail;
    int         size;
    tstrategy  strategyarg;
    tstrategy  strategyused;
    double      disorder;
    int         bench;
    int         ops;
}   tstack;
tstack ft_stack_new(int create_ops)
{
    t_stack stack;
    int     i;

stack = ftcalloc(1, sizeof(tstack)); if (!stack) return (free(stack), NULL); stack->strategyarg = STRATADAPTIVE; stack->strategyused = STRATADAPTIVE; stack->head = NULL; stack->tail = NULL; stack->ops = NULL; if (createops) {

stack->ops = ftcalloc(1, sizeof(int)); if (!stack->ops) return (free(stack), NULL); stack->ops = ftcalloc(OPTOTAL+1, sizeof(int)); if (!stack->ops) return (free(stack), free(stack->ops), NULL); i = 0; while (i < OP_TOTAL) (stack->ops)[i++] = 0; (stack->ops)[OP_TOTAL] = 0; } return (stack); }

void    ft_free_stack(t_stack stack)
{
    tnode  *node;
    tnode  tmp;

if (!stack) return ; node = stack->head; while (node) { tmp = node->next; free(node); node = tmp; } stack->head = NULL; stack->tail = NULL; if (stack->ops != NULL) { if (stack->ops) { free(stack->ops); stack->ops = NULL; } free(stack->ops); stack->ops = NULL; } free(stack); }

Throughout the rest of the code, when you want to use the contents of the ops array, use variable->ops instead of variable->ops.

When you want to reuse the ops array, do:

b->ops = calloc(1, sizeof(int));
b->ops = a-ops;

You could implement this as part of ftstacknew(). Instead of passing int createops, pass int *reuseops. If this is NULL, create a new ops array, otherwise use it as the old array to point to.

BTW, there's no point in doing stack = NULL; at the end of ftfreestack(). This is a local variable that goes away when the function ends, assigning it has no effect.