Exercise: Implement strlen(), strcpy(), strcat(), memcpy()¶
Tools: GCC, Make
Goal¶
Implement four of the C library's string functions yourself, from scratch: strlen(), strcpy(), strcat(), memcpy().
Background¶
A C string is a sequence of bytes terminated by '\0'.
It does not carry its own length: nothing in the representation says where the string ends except the terminator itself.
Every function that needs the length must therefore go and find it, byte by byte.
memcpy() is different: it is told how many bytes to copy, knows nothing about '\0', and takes void * rather than char *.
Directory Contents¶
mystring.c: where to implement the four string functions.mystring.h: header file with the declaration of the functions inmystring.c, included inmain.c.main.c: contains themain()function where to implement calls (and tests) to the four string functions.Makefile: build the program.README.md: this file.FURTHER.md: optional further exercises and instructions, to be worked on either at home or, if time allows it, after the lab session.
Build & Run¶
Build with:
Run with:
Initially, every check fails, as no functions are implemented and no calls are made.
Your Tasks¶
Open mystring.c and main.c and fill in the four TODOs in each file.
Implement and test one function at a time.
Implement the function in mystring.c, implement the call and test in main.c.
-
Implement
my_strlen()in theTODO 1section inmystring.c. It counts the number of characters up to, not including, theNUL-terminator (\0).Call
my_strlen()(andstrlen()) in theTODO 1section inmain.c. Build and run the program. Check to see if the result is the same. -
Implement
my_strcpy()in theTODO 2section inmystring.c. It copies thesrcstring to thedeststring, with theNUL-terminator included. It returnsdest.Call
my_strcpy()(andstrcpy()) in theTODO 2section inmain.c. Check to see if the result is the same. -
Implement
my_strcat()in theTODO 3section inmystring.c. It appends thesrcstring to thedeststring, with theNUL-terminator included. It returnsdest.Call
my_strcat()(andstrcat()) in theTODO 3section inmain.c. Check to see if the result is the same. -
Implement
my_memcpy()in theTODO 4section inmystring.c. It copies exactlynbytes fromsrctodest. It returnsdest.my_memcpyreceivesvoid *, which you can neither dereference nor advance. Assign it to anunsigned char *first.Call
my_memcpy()(andmemcpy()) in theTODO 4section inmain.c. Check to see if the result is the same.
Check Your Work¶
At the end, all TODOs are filled (both in mystring.c and in main.c).
And all tests in the main() function in main.c pass.