Skip to content

Instantly share code, notes, and snippets.

@aflaag
Last active April 16, 2023 09:09
Show Gist options
  • Save aflaag/11a6eb13c90810e9735554283f0c1517 to your computer and use it in GitHub Desktop.
Save aflaag/11a6eb13c90810e9735554283f0c1517 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Clones the available portion of the first block into the second one */
int clone_block(char* m1, char* m2, const int size_m1, const int size_m2) {
int size = size_m1 <= size_m2 ? size_m1 : size_m2;
memcpy(m2, m1, size * sizeof(char));
return memcmp(m1, m2, size);
}
/* Returns the power of a number. */
int powi(int n, int exp) {
int tot = 1;
for (int i = 0; i < exp; i++) {
tot *= n;
}
return tot;
}
/* Returns the integer represented by the input string. */
int pos_atoi(char* str) {
int tot = 0;
int exp = strlen(str) - 1;
for (int i = 0; str[i] != '\0'; i++) {
int curr_char = str[i] - '0';
if (curr_char < 0 || curr_char > 9) {
return -1;
}
tot += powi(10, exp) * curr_char;
exp--;
}
return tot;
}
int set_block(char* ptr, int size) {
char input[size];
if (fgets(input, size + 1, stdin) == NULL) {
return -1;
}
memcpy(ptr, input, size * sizeof(char));
return 0;
}
int main(int argc, char* argv[]) {
// check if there are enough arguments
if (argc < 3) {
printf("Missing memory size.\n");
exit(0);
}
// convert arguments into integers
int size_m1 = pos_atoi(argv[1]);
int size_m2 = pos_atoi(argv[2]);
if (size_m1 == -1) {
printf("Invalid M1 memory size argument.\n");
exit(0);
}
if (size_m2 == -1) {
printf("Invalid M2 memory size argument.\n");
exit(0);
}
// allocate m1
char* m1 = (char*) calloc(size_m1, sizeof(char));
if (m1 == NULL) {
printf("M1 not allocated.\n");
exit(0);
}
printf("M1 allocated correctly, with size %d.\n", size_m1);
// initialize m1
int error_code = set_block(m1, size_m1);
if (error_code == -1) {
printf("Couldn't initialize M1.\n");
free(m1);
exit(0);
}
// allocate m2
char* m2 = (char*) calloc(size_m2, sizeof(char));
if (m2 == NULL) {
printf("M2 not allocated.\n");
free(m1);
exit(0);
}
printf("M2 allocated correctly, with size %d.\n", size_m2);
// clone (a portion of) m1 into m2
if(clone_block(m1, m2, size_m1, size_m2)) {
printf("M1 was not cloned into M2.\n");
} else {
printf("M1 was successfully cloned into M2.\n");
printf("M1: %s\n", m1);
printf("M2: %s\n", m2);
}
free(m1);
free(m2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment