/* * Fixed code for CSE 333 Section 2 * 1. Draw a memory diagram for the execution to identify errors. * 2. Use gdb and valgrind to identify sources of runtime, logical, * and memory errors. * 3. Clean up the code style. */ #include // strcpy, strlen #include // printf #include // malloc, NULL, free, EXIT_FAILURE, EXIT_SUCCESS // WordCount is considered a "small" struct typedef struct word_st { char* word; int count; } WordCount; /* * NOTE: CapitalizeWord could be converted to take WordCount wc instead * because the copied struct would get a copy of the char* word, which points * to the same C-string. This _could_ be preferred stylistically because * WordCount is a small struct, but we are keeping it a pointer to better * convey the intent to modify the struct instance. */ // Capitalize the first letter in the word void CapitalizeWord(WordCount* wc_ptr); // Increment the count by 1 void IncreaseCount(WordCount* wc_ptr); /* * NOTE: Return value changed to a pointer and responsibility to free passed to * the caller. Since structs are passed-by-value, there would be no way to * directly return a copy of the malloc'ed struct AND free it properly within * this function. * NOTE: Values of argument are only being read, so passing a copy is preferred * because WordCount is a small struct. */ // Return a new WordCount with the letters of word in reverse order and a // count of 0. Returns NULL on allocation failure. WordCount* ReverseWord(WordCount wc); int main(int argc, char* argv[]) { char comp[] = "computer"; WordCount comp_count = {comp, 5}; WordCount* comp_ptr = &comp_count; // expecting "1. computer, 5" printf("1. %s, %d\n", comp_ptr->word, comp_ptr->count); IncreaseCount(comp_ptr); // expecting "2. computer, 6" printf("2. %s, %d\n", comp_ptr->word, comp_ptr->count); CapitalizeWord(comp_ptr); // expecting "3. Computer, 6" printf("3. %s, %d\n", comp_ptr->word, comp_ptr->count); comp_ptr = ReverseWord(*comp_ptr); if (comp_ptr == NULL) { return EXIT_FAILURE; } // expecting "4. retupmoC, 0" printf("4. %s, %d\n", comp_ptr->word, comp_ptr->count); free(comp_ptr->word); free(comp_ptr); return EXIT_SUCCESS; } void IncreaseCount(WordCount* wc_ptr) { wc_ptr->count += 1; } void CapitalizeWord(WordCount* wc_ptr) { wc_ptr->word[0] &= ~0x20; } WordCount* ReverseWord(WordCount wc) { WordCount* rev = (WordCount*) malloc(sizeof(WordCount)); if (rev == NULL) { return NULL; } rev->word = (char*) malloc( (strlen(wc.word) + 1) * sizeof(char) ); if (rev->word == NULL) { return NULL; } strcpy(rev->word, wc.word); rev->count = 0; char ch; int L = 0, R = strlen(rev->word) - 1; while (L < R) { ch = rev->word[L]; rev->word[L] = rev->word[R]; rev->word[R] = ch; L++; R--; } return rev; }