c_mem_safety/expanded.cpp

36 lines
1.0 KiB
C++
Raw Permalink Normal View History

#include <stdio.h>
enum HANDLE_STATE {
HANDLE_CREAT,
HANDLE_DESTR
};
struct Vektor {
int count;
int *v;
}; struct Vektor_raiicpp; static inline void Vektor_lifetime_handler( enum HANDLE_STATE state, struct Vektor_raiicpp *self, void *data); struct Vektor_raiicpp : public Vektor { inline Vektor_raiicpp(void *data) { Vektor_lifetime_handler(HANDLE_CREAT, this, data); } inline ~Vektor_raiicpp() { Vektor_lifetime_handler(HANDLE_DESTR, this, nullptr); } } static inline void Vektor_lifetime_handler( enum HANDLE_STATE state, struct Vektor_raiicpp *self, void *data) {
if(state == HANDLE_CREAT) {
self->count = *(int*) data;
self->v = calloc(self->count, sizeof(int));
} else if (state == HANDLE_DESTR){
if(self->v) free(self->v);
}
}
int main() {
int n;
printf("Number of elements to sum: ");
scanf(" %d", &n);
Vektor_raiicpp data(&n);;
for(int i = 0; i < data.count; ++i) {
scanf(" %d", &n);
data.v[i] = n;
}
n = 0; for(int i = 0; i < data.count; ++i) n += data.v[i];
printf("Sum: %d\n", n);
return 0;
}