Menu
CoddyTech

Cleanup on Every Path

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

C++ RAII runs destructors during normal scope exit and exception unwinding. C has no destructors or exception unwinding; a release operation must appear on every explicit ownership path.

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

C++ example

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
struct Resource{~Resource(){std::cout<<"close\n";}};
int main(){
{Resource resource;std::cout<<"work\n";}
}

C++ 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 C++ Developers

Practice on your own: Online C compiler