Menu
CoddyTech

Cleanup on Every Path

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

Java try-with-resources invokes close on scope exit. C has no corresponding automatic destructor protocol: every ownership path, including an early error return, must release its resources explicitly.

Free owned allocations on success and failure paths. C return does not run a destructor or a deferred cleanup block.

Java example


public class Main {
static class Resource implements AutoCloseable{public void close(){System.out.println("close");}}
public static void main(String[] args) {
try(Resource r=new Resource()){System.out.println("work");}
}
}

Java output:

work
close

C example

#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;
}

C output:

6
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 Java Developers

Practice on your own: Online C compiler