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
closeC 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:
6Challenge
EasyImplement 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;}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in C for C++ Developers
1Compile and Compute
Run C Across FilesPrinting and CommentsTypes and InitializationInteger Division and RangeFloating ArithmeticRecap: Receipt Total4Functions and Interfaces
Function Arguments Are ValuesHeaders and LinkageMultiple Results via PointersConst Views and MutationRecap: Price Breakdown2Decisions and Loops
Booleans and BranchesLogical OperatorsSwitch and Enumerated CasesLoop Bounds and ProgressRecap: Admission Rules5Pointers and Structs
Addresses and DereferencingPointer Steps and BoundariesRecords as Struct ValuesMutable Struct APIsRecap: Point Translation8Tagged Data and Composition
Enums and Tagged RecordsFunction Pointer CallbacksSorting with a ComparatorStateful Policy CompositionCleanup on Every PathRecap: Select a PolicyPractice on your own: Online C compiler