aboutsummaryrefslogtreecommitdiff
path: root/challenge-206
diff options
context:
space:
mode:
authorPaulo Custodio <pauloscustodio@gmail.com>2023-03-11 22:43:15 +0000
committerPaulo Custodio <pauloscustodio@gmail.com>2023-03-11 22:43:15 +0000
commit48cb0f7ba25f14244c608c027774fc15feddb11c (patch)
treeb533ea30133824067ac353ca4ed99baac0d1b4d5 /challenge-206
parente2b3a9b9cbd927d33516c42b88ec16bf0aebcb58 (diff)
downloadperlweeklychallenge-club-48cb0f7ba25f14244c608c027774fc15feddb11c.tar.gz
perlweeklychallenge-club-48cb0f7ba25f14244c608c027774fc15feddb11c.tar.bz2
perlweeklychallenge-club-48cb0f7ba25f14244c608c027774fc15feddb11c.zip
Add Perl, C, C++ and Forth solutions
Diffstat (limited to 'challenge-206')
-rw-r--r--challenge-206/paulo-custodio/c/ch-1.c10
-rw-r--r--challenge-206/paulo-custodio/c/ch-2.c14
2 files changed, 20 insertions, 4 deletions
diff --git a/challenge-206/paulo-custodio/c/ch-1.c b/challenge-206/paulo-custodio/c/ch-1.c
index 10e7e64ece..9d583896b7 100644
--- a/challenge-206/paulo-custodio/c/ch-1.c
+++ b/challenge-206/paulo-custodio/c/ch-1.c
@@ -28,6 +28,14 @@ Output: 15
#include <stdio.h>
#include <stdlib.h>
+void* check_mem(void* p) {
+ if (!p) {
+ fputs("Out of memory", stderr);
+ exit(EXIT_FAILURE);
+ }
+ return p;
+}
+
int minutes(const char* str) {
int hours = 0, minutes = 0;
if (sscanf(str, "%d:%d", &hours, &minutes) == 2)
@@ -48,7 +56,7 @@ int main(int argc, char* argv[]) {
}
int num_items = argc+1;
- int* items = malloc(num_items * sizeof(int));
+ int* items = check_mem(malloc(num_items * sizeof(int)));
for (int i = 0; i < num_items-1; i++)
items[i] = minutes(argv[i]);
qsort(items, num_items-1, sizeof(int), compare);
diff --git a/challenge-206/paulo-custodio/c/ch-2.c b/challenge-206/paulo-custodio/c/ch-2.c
index 79e72feeb5..aa72e3f4b3 100644
--- a/challenge-206/paulo-custodio/c/ch-2.c
+++ b/challenge-206/paulo-custodio/c/ch-2.c
@@ -45,12 +45,20 @@ typedef struct {
int* items;
} IList;
+void* check_mem(void* p) {
+ if (!p) {
+ fputs("Out of memory", stderr);
+ exit(EXIT_FAILURE);
+ }
+ return p;
+}
+
IList* ilist_new(size_t count) {
- IList* list = calloc(1, sizeof(IList));
+ IList* list = check_mem(calloc(1, sizeof(IList)));
assert(list);
if (count) {
list->count = count;
- list->items = calloc(count, sizeof(int));
+ list->items = check_mem(calloc(count, sizeof(int)));
assert(list->items);
}
return list;
@@ -63,7 +71,7 @@ void ilist_free(IList* list) {
void ilist_push(IList* list, int elem) {
list->count++;
- list->items = realloc(list->items, list->count * sizeof(int));
+ list->items = check_mem(realloc(list->items, list->count * sizeof(int)));
assert(list->items);
list->items[list->count - 1] = elem;
}