1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miniunit.h"
// Note for HW06: If you have conditional jump based on uninitialized
// value, there's a very good chance you forgot to write the '\0' at the
// end of your string. Make sure you understand why this error happens.
#define mu_check_strings_eq(s1, s2) \
mu_check(strcmp((s1), (s2)) == 0)
// Tip: In your mu_check(…) you should have parenthesized (condition)
// in the rhs of the #define so that you will have no precedence
// issues here. If this doesn't make sense, just do it anyway.
//
// strcmp(…) returns 0 when the strings are EQUAL.
char* mystrdup(char* s) {
// Find LENGTH
size_t len = 0;
while(s[len] != '\0') { // while(…) { … } is a kind of conditional jump
len++;
}
// ALLOCATE memory for new string
char* new_s = malloc((len + 1) * sizeof(*new_s)); // Don't forget '*'
// !!! Don't forget to include the null terminator in your calculation
// of how many bytes to allocate with malloc(…).
//
// Recommendation: Allocate only as many bytes as you need--and no more.
// POPULATE new string with characters, including the null terminator
for(int i = 0; i < len; i++) {
new_s[i] = s[i];
}
new_s[len] = '\0'; // Don't forget the null terminator!!!
return new_s;
}
int _test_easy() {
mu_start();
// This is just a step toward a better solution.
char* expected = "protein";
char* actual = mystrdup(expected);
mu_check_strings_eq(expected, actual);
free(actual);
mu_end();
}
int main(int argc, char* argv[]) {
mu_run(_test_easy);
/* char* s1 = mystrdup("protein"); */
/* //printf("s1 == \"%s\"\n", s1); */
/* log_str(s1); */
/* free(s1); */
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.