Lab04 - Strings and (de)allocation

Valgrind

  • use valgrind for memory leak detection
  • can detect forgotten allocated memory and the exact location of out-of-bound access
  • can report using uninitialized variables/memory
  • for better output, compile your program with -g flag
  • valgrind ./your-program

Documentation

  • learn to understand the function declaration (the name, return type, and parameters)
  • the definition (code to be executed) might not always be available

Strings

  • Remember you can use #include <string.h> for helper functions
  • Let's declare an array of characters, and then ask the user for their first name
  • Print the name, its length, and say if it's the same as your own name
  • You can use the function strcmp to compare the strings, will return zero if the same

Dynamic memory

  • Modify your program to use dynamic memory for the name
  • Ask the user for other names
  • Use realloc to make the original name string bigger
  • Use memcpy to append the additional name to the original name/string

Task 1

  • Write a program which allows the user to enter “infinite” amounts of text, and will keep appending it to a string (char array).
  • When they press enter, it will output the current string.
  • If they enter a certain character, it will close.
  • Use the getchar() function to get letters from the command line.
  • You will need to use malloc() and realloc() to control the memory.
  • Don’t forget to use free() at the end to free the memory.

Task 2

  • Update the previous code to read a whole word from the input.
  • Implement your own version of the strcmp() function from the string.h library.
  • Hard-code your name into your program, and ask the user to input words.
  • If it matches your name, print a message!
  • Can you make it case insensitive?

reference solutions

courses/be5b99cpl/labs/lab04.txt · Last modified: 2024/10/16 19:32 by janotjir