Menu
CoddyTech

Cleanup on Every Path

Lesson 41 of 48 in Coddy's C for Python Developers course.

Python uses context managers or finally to release resources. C must arrange cleanup explicitly on success and failure. One cleanup path can simplify ownership, but correctness depends on releasing each acquired resource exactly once and not using it afterward.

Python

values=[1,2,3]
print(sum(values))

C17

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
int *values=malloc(3*sizeof *values);if(!values)return 1;values[0]=1;values[1]=2;values[2]=3;int total=values[0]+values[1]+values[2];free(values);printf("%d\n",total);
return 0;
}

Porting rule

Release owned resources on every exit path, then stop using them.

challenge icon

Challenge

Easy

Implement sum_owned_copy(values,n,out): allocate a private copy, reject any negative input without changing *out, otherwise write the sum. Free the private copy on both paths. Empty input succeeds with sum zero. Return false on validation or allocation failure. The driver prints sum or invalid and checks output atomicity.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;int out=77;if(sum_owned_copy(values,n,&out))printf("%d\n",out);else {if(out!=77)return 3;puts("invalid");}return 0;}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C for Python Developers

Practice on your own: Online C compiler