use an exit function, rather than manually freeing, since it's saver for when errors happen
This commit is contained in:
16
src/main.c
16
src/main.c
@@ -20,17 +20,22 @@ typedef struct dynrdat {
|
|||||||
ull dat[];
|
ull dat[];
|
||||||
} dynrdat;
|
} dynrdat;
|
||||||
|
|
||||||
|
dynrdat* rdat = NULL;
|
||||||
|
|
||||||
static inline ull pow2_ceil(ull x) {
|
static inline ull pow2_ceil(ull x) {
|
||||||
x -= !!x; // if x=0, remains 0; else x -= 1
|
x -= !!x; // if x=0, remains 0; else x -= 1
|
||||||
int lz = __builtin_clzll(x | 1); // get leading zeroes
|
int lz = __builtin_clzll(x | 1); // get leading zeroes
|
||||||
return (~0ULL >> lz) + 1; // bit-shift the maximum value by this amount of leading zeroes
|
return (~0ULL >> lz) + 1; // bit-shift the maximum value by this amount of leading zeroes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void quit(void) {
|
||||||
|
free(rdat);
|
||||||
|
}
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
// return the result if no input
|
// return the result if no input
|
||||||
if (argc <= 1) return printf("%s\n", (clock() & 1) ? "heads" : "tails");
|
if (argc <= 1) return printf("%s\n", (clock() & 1) ? "heads" : "tails");
|
||||||
|
atexit(quit);
|
||||||
dynrdat* rdat = NULL;
|
|
||||||
|
|
||||||
// loop through arguments
|
// loop through arguments
|
||||||
for (unsigned i = 1; i < (unsigned)argc; ++i) {
|
for (unsigned i = 1; i < (unsigned)argc; ++i) {
|
||||||
@@ -47,10 +52,7 @@ int main(int argc, char** argv) {
|
|||||||
size_t cap = pow2_ceil(c + !!mod);
|
size_t cap = pow2_ceil(c + !!mod);
|
||||||
if (!rdat || rdat->cap < cap) {
|
if (!rdat || rdat->cap < cap) {
|
||||||
void* ptr = realloc(rdat, sizeof(dynrdat) + sizeof(ull) * cap);
|
void* ptr = realloc(rdat, sizeof(dynrdat) + sizeof(ull) * cap);
|
||||||
if (!ptr) {
|
if (!ptr) error(1, "insufficient memory\n", );
|
||||||
free(rdat);
|
|
||||||
error(1, "insufficient memory\n", );
|
|
||||||
}
|
|
||||||
|
|
||||||
rdat = ptr;
|
rdat = ptr;
|
||||||
rdat->cap = cap;
|
rdat->cap = cap;
|
||||||
@@ -84,7 +86,5 @@ int main(int argc, char** argv) {
|
|||||||
printf("results:\n heads: %llu\n tails: %llu\n", headsc, tailsc);
|
printf("results:\n heads: %llu\n tails: %llu\n", headsc, tailsc);
|
||||||
}
|
}
|
||||||
|
|
||||||
free(rdat);
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user