soft-exp/ex03/mixed/mixed04.c
2025-05-22 10:44:24 +02:00

82 lines
1.7 KiB
C
Executable File

#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_ELEMENTS 8
typedef struct creds creds_t;
typedef struct creds {
void (*welcome)(void);
uint64_t buffer[NUM_ELEMENTS];
} creds_t;
static creds_t *creds;
/* internal prototypes */
static void insert(uint64_t value, int64_t index);
static void print(void);
static void s3cr3t(void);
/* entry point */
int main(int argc, char **argv) {
if (argc < 3) {
printf("usage: %s <hex value> <index>\n", argv[0]);
return -1;
}
char *endptr;
errno = 0;
uint64_t value = (uint64_t)strtoull(argv[1], &endptr, 16);
if (errno || *endptr) {
fprintf(stderr, "Conversion error, non-convertible part: %s\n", endptr);
exit(EXIT_FAILURE);
}
errno = 0;
uint64_t index = (uint64_t)strtoull(argv[2], &endptr, 10);
if (errno || *endptr) {
fprintf(stderr, "Conversion error, non-convertible part: %s\n", endptr);
exit(EXIT_FAILURE);
}
if (index < 0) {
fprintf(stderr, "Negative index\n");
exit(EXIT_FAILURE);
}
creds = (creds_t *)calloc(1, sizeof(creds_t));
if (!creds) {
perror("calloc");
return -1;
}
creds->welcome = print;
insert(value, index);
creds->welcome();
free(creds);
return 0;
}
/* internal function definitions */
static void insert(uint64_t value, int64_t index) {
if (index >= NUM_ELEMENTS) {
fprintf(stderr, "Invalid index!\n");
exit(EXIT_FAILURE);
}
creds->buffer[index] = value;
}
static void print(void) {
for (int i = 0; i < NUM_ELEMENTS; ++i) {
printf("Index %d: %#lx\n", i, creds->buffer[i]);
}
}
static void s3cr3t(void) { printf("You've gathered secret material!\n"); }