Course Topics
C Basics Introduction and Setup Syntax and Program Structure Comments and Documentation Compiling and Running C Programs Exercise Variables and Data Types Variables and Declaration Data Types (int, float, char, double) Constants and Literals Type Conversion and Casting Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Standard Input/Output (scanf, printf) Format Specifiers File Input/Output Exercise Control Flow - Conditionals If Statements If-Else Statements Switch Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Do-While Loops Loop Control (break, continue) Nested Loops Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Recursion Exercise Arrays One-Dimensional Arrays Multi-Dimensional Arrays Array Operations Strings as Character Arrays Exercise Pointers Introduction to Pointers Pointer Arithmetic Pointers and Arrays Pointers and Functions Dynamic Memory Allocation Exercise Strings String Handling String Functions (strlen, strcpy, strcmp) String Manipulation Exercise Structures Defining Structures Structure Members Arrays of Structures Pointers to Structures Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Positioning Exercise Memory Management Static vs Dynamic Memory malloc() and free() Memory Leaks Best Practices Exercise Advanced Topics Preprocessor Directives Macros Header Files Modular Programming Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

String Functions (strlen, strcpy, strcmp)

Introduction

Welcome to the String Functions tutorial! In this lesson, we will delve into three essential C functions that manipulate strings: strlen, strcpy, and strcmp. Understanding these functions is crucial for working with strings in C, as they allow you to calculate the length of a string, copy one string to another, and compare two strings for equality, respectively.

Core Concepts

Let's take a closer look at each function:

strlen

What it does: The strlen function calculates the length of a string, returning the number of characters (excluding the null character '\0').

Key terminology: Character, String, Null character ('\0')

Example:

#include <stdio.h>
#include <string.h>

int main() {
  char str[] = "Hello, World!";
  int len = strlen(str);
  printf("The length of the string is %d\n", len);
}

Output: The length of the string is 13

strcpy

What it does: The strcpy function copies the source string to the destination string, overwriting the existing contents of the destination string.

Example:

#include <stdio.h>
#include <string.h>

int main() {
  char src[] = "Source String";
  char dest[20];
  strcpy(dest, src);
  printf("The copied string is %s\n", dest);
}

Output: The copied string is Source String

strcmp

What it does: The strcmp function compares two strings lexicographically (character by character) and returns an integer indicating the relationship between the strings: 0 if they are equal, a negative value if the first string comes before the second alphabetically, or a positive value if the first string comes after.

Example:

#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Apple";
  char str2[] = "Banana";
  int result = strcmp(str1, str2);
  if (result < 0) {
    printf("%s comes before %s\n", str1, str2);
  } else if (result > 0) {
    printf("%s comes after %s\n", str1, str2);
  } else {
    printf("%s is equal to %s\n", str1, str2);
  }
}

Output: Apple comes before Banana

Practical Examples

Here are real-world code examples demonstrating the use of strlen, strcpy, and strcmp.

Using strlen for dynamic memory allocation

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
  char *input;
  int len;

  printf("Enter a string: ");
  fgets(input, sizeof(input), stdin);

  // Remove the newline character and calculate length
  len = strlen(input) - 1;
  input[len] = '\0';

  char *copy = malloc((len + 1) * sizeof(char));
  strcpy(copy, input);

  printf("The copied string is %s\n", copy);
  free(copy); // Don't forget to free allocated memory!
}

Common Issues and Solutions (CRITICAL SECTION)

Buffer Overflow Error

What causes it: Writing more characters than the capacity of a string buffer.

#include <stdio.h>
#include <string.h>

int main() {
  char str[5]; // Only enough space for 4 characters plus null terminator
  strcpy(str, "Hello"); // This will cause a buffer overflow error!
}

Error message:

Segmentation fault (core dumped)

Solution: Ensure that the string buffer has enough capacity to hold the source string and the null terminator.

Why it happens: The strcpy function copies characters from the source string until it encounters a null character, so if there isn't enough space in the destination buffer, memory beyond its bounds will be overwritten, leading to undefined behavior.

How to prevent it: Allocate an appropriate size for the destination string before using strcpy.

Null Pointer Error

What causes it: Passing a null pointer as the destination or source string in strcpy and strcmp, respectively.

#include <stdio.h>
#include <string.h>

int main() {
  char *dest = NULL; // Null pointer
  strcpy(dest, "Hello"); // This will cause a null pointer error!
}

Error message:

Segmentation fault (core dumped)

Solution: Always initialize pointers to non-null values before using them with strcpy or strcmp.

Why it happens: When a null pointer is passed as the destination or source string, the program tries to access memory at an invalid location, resulting in a segmentation fault.

How to prevent it: Initialize pointers to valid memory addresses before using them with strcpy or strcmp.

Incorrect Comparison Error

What causes it: Using strcmp to compare strings that are not properly terminated (i.e., do not have a null character at the end).

#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Apple";
  char str2[5] = "Bana"; // Incorrectly terminated string
  int result = strcmp(str1, str2); // This will cause incorrect comparison!
}

Error message: None, but the comparison result may be unexpected.

Solution: Ensure that both strings are properly terminated with a null character.

Why it happens: The strcmp function compares characters until it encounters a null character or finds a difference between the two strings. If one of the strings is not properly terminated, strcmp will continue comparing beyond its intended length, leading to incorrect results.

How to prevent it: Properly terminate all strings with a null character before using them with strcmp.

Best Practices

  • Always check the capacity of your string buffers and ensure they are large enough for the source string plus the null terminator when using strcpy.
  • Use strlen to dynamically allocate memory for strings.
  • Initialize pointers to non-null values before using them with strcpy or strcmp.
  • Properly terminate all strings with a null character before using them with strcmp.
  • Consider using library functions like strncpy, strncat, and memcmp for more advanced string manipulation and comparison tasks.

Key Takeaways

In this tutorial, you learned about the essential C string functions strlen, strcpy, and strcmp. You now have the ability to:

  • Calculate the length of a string
  • Copy one string to another
  • Compare two strings for equality

Building on this foundation, you can delve deeper into working with strings in C and master more advanced techniques for manipulating them. Happy coding!