DEV Community

Cover image for Understanding Strings in C: From Basics to Best Practices
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on

Understanding Strings in C: From Basics to Best Practices

The C programming language is powerful, fast, and close to the hardware—but it also places a significant amount of responsibility on the programmer. One of the most common sources of bugs, crashes, and security vulnerabilities in C programs is string handling.


What Is a String in C?

Unlike many modern languages, C does not have a built-in string type.

In C, a string is:

A sequence of characters stored in an array of char, terminated by a null character ('\0').

Example:

char name[] = "Alice";
Enter fullscreen mode Exit fullscreen mode

Internally, this is stored as:

'A' 'l' 'i' 'c' 'e' '\0'
Enter fullscreen mode Exit fullscreen mode

The null terminator tells the program where the string ends. Without it, functions cannot determine the string length and may read invalid memory.


Declaring and Initializing Strings

Using Character Arrays

char str1[6] = "Hello";
Enter fullscreen mode Exit fullscreen mode

This allocates space for 6 characters: 5 letters + '\0'.

Without Explicit Size

char str2[] = "World";
Enter fullscreen mode Exit fullscreen mode

The compiler automatically allocates enough memory, including the null terminator.

Using Pointers (Read-Only Strings)

char *str3 = "Hello";
Enter fullscreen mode Exit fullscreen mode

This points to a string literal, which is typically stored in read-only memory. Modifying it results in undefined behavior.


Input and Output of Strings

Printing Strings

printf("%s\n", str1);
Enter fullscreen mode Exit fullscreen mode

The %s format specifier prints characters until it encounters '\0'.

Reading Strings (Be Careful!)

char buffer[20];
scanf("%19s", buffer);
Enter fullscreen mode Exit fullscreen mode

Always limit input size to prevent buffer overflow.

❌ Never use gets() — it is unsafe and removed from the C standard.


Common String Functions (<string.h>)

C provides a standard library for string manipulation.

strlen – Length of a String

size_t len = strlen(str1);
Enter fullscreen mode Exit fullscreen mode

Returns the number of characters excluding the null terminator.


strcpy – Copy Strings (Unsafe!)

char dest[10];
strcpy(dest, "Hello");
Enter fullscreen mode Exit fullscreen mode

⚠️ strcpy does not check buffer size.

Safer alternative:

strncpy(dest, "Hello", sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
Enter fullscreen mode Exit fullscreen mode

strcat – Concatenate Strings

char result[20] = "Hello ";
strcat(result, "World");
Enter fullscreen mode Exit fullscreen mode

Again, make sure the destination buffer is large enough.


strcmp – Compare Strings

if (strcmp(str1, str2) == 0) {
    // strings are equal
}
Enter fullscreen mode Exit fullscreen mode

It compares strings lexicographically, not by memory address.


Strings and Memory

Strings in C are tightly coupled with memory management.

Stack vs Heap

char local[20];              // stack
char *dynamic = malloc(20); // heap
Enter fullscreen mode Exit fullscreen mode

When using dynamic memory:

free(dynamic);
Enter fullscreen mode Exit fullscreen mode

Failing to free memory results in memory leaks.


Common Mistakes with C Strings

  1. Forgetting the null terminator
  2. Buffer overflows
  3. Modifying string literals
  4. Using sizeof instead of strlen
  5. Comparing strings using ==

Example of a wrong comparison:

if (str1 == str2) { } // WRONG
Enter fullscreen mode Exit fullscreen mode

Correct way:

if (strcmp(str1, str2) == 0) { }
Enter fullscreen mode Exit fullscreen mode

Best Practices for Working with Strings in C

  • Always allocate enough space for '\0'
  • Prefer safer alternatives (snprintf, strncat)
  • Validate input sizes
  • Avoid deprecated functions
  • Use dynamic memory carefully
  • Write your own utility functions when needed

Final Thoughts

C strings are simple in concept but dangerous in practice if mishandled. Understanding how they work internally—especially memory layout and null termination—is essential for writing robust, secure, and professional C code.

Mastering strings in C will significantly improve your skills as a systems programmer and help you avoid many real-world bugs.

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Your declaration of str3 should be:

char const *str3 = "Hello";
Enter fullscreen mode Exit fullscreen mode

You never mention that strcmp returns values < 0 and > 0 and what those mean.