Explain the main string library functions and their precautions.
5 marks
Answer in brief
The string.h header declares common operations on null-terminated strings and memory. Each function still requires valid arguments and sufficient storage.
Main functions
strlen(s) returns the number of bytes before the null terminator as size_t.
strcpy(destination, source) copies the source and its terminator.
strcat(destination, source) appends the source after the destination’s existing string.
strcmp(a, b) compares two strings and returns a negative, zero or positive value.
strchr(s, ch) locates the first matching character, or returns NULL when absent.
Capacity requirements
strcpy needs enough writable destination positions for source length plus one. strcat needs enough for both lengths plus one, and destination must already contain a valid string. These functions do not receive the destination’s capacity and cannot automatically grow it.
Overlap and bounded forms
strcpy and strcat require non-overlapping source and destination strings. For overlapping regions within one array, memmove is designed for moving a specified byte count safely. strncpy is not a general guarantee of termination: if the source is at least the specified count, the copied result is not automatically terminated.
Comparison and length
Use strcmp rather than == to compare text contents. Check only its result’s sign, not an assumed exact -1 or 1. Use %zu for the size_t returned by strlen. The length excludes the terminator, while required storage includes it.
Complexity
strlen and strcpy perform work proportional to the relevant string length. A single strcat must find the destination end and copy the source, giving O(d + s) work. strcmp examines a prefix until a difference or end is reached, up to O(min(m, n) + 1) byte comparisons. No growing auxiliary array is required by these basic operations.
Reference table
↔ Scroll horizontally on a small screen
String function requirements
Function
Purpose
Key requirement
strlen
Count bytes before terminator
Valid terminated source
strcpy
Copy with terminator
Enough capacity; no overlap
strcat
Append source
Terminated destination; enough space; no overlap
strcmp
Compare contents
Both sources terminated
strchr
Find character
Valid terminated source
memmove
Move specified byte count
Valid source/destination ranges; overlap allowed
Related exam questions
Related questions in the string functions category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
September/October 2021 · Q7(b) · 8 marks
Describe string library functions with syntax and an example program.