String Pitfalls, Quiz, Interview- C Programming Tutorials For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

String Pitfalls, Quiz, Interview

Learn the seven classic C string mistakes, how to fix them, then test yourself with a quiz and embedded C interview questions.

What You Will Learn

  • Why a pointer needs real storage before you write through it
  • Why string literals must not be modified and how const helps
  • Why strcat needs a string and why array names cannot be assigned
  • How dangling pointers and pointer parameters really behave
  • How to answer common embedded C interview questions on strings

Prerequisites

  • Lectures cp9_48 to cp9_53
  • Arrays, pointers and functions
  • Basic understanding of stack memory

The answer key at the end of the Strings chapter is a list of programs that look innocent and fail in instructive ways. In this final lecture of the batch, part of our free C programming course, we turn each failure into a rule you can remember. You will learn the most common C string mistakes, why each one happens, and how to fix it. Then you will test yourself with a quiz and a set of interview questions on embedded C programming and strings.

These bugs are the ones that cause real field failures: a pointer that was never set, text that cannot be modified, a buffer that outlives its function. Each is a few characters of source, and each is easy to avoid once you know the memory model behind it.

Mistake 1: Reading Into a Pointer That Points Nowhere

Declaring char *str; creates a pointer variable but no text storage. A local pointer holds whatever bytes were on the stack, so handing it to an input function such as fgets or scanf makes the function write to a random address. The same trap appears with an array of pointers: each element is uninitialised until you assign something valid to it.

char *str;                    /* points nowhere */
fgets(str, 32, stdin);        /* BUG: writes to a random address */

char line[32];                /* FIX: real storage */
fgets(line, sizeof line, stdin);
A pointer is only an address
wrong
str→???random memory
right
line[32]→32 bytes you own

Rule: before any function writes through a pointer, ask which object that pointer points to. If the answer is nothing, you have a bug.

Mistake 2: Modifying a String Literal

A string literal such as "Good" usually lives in read-only memory. A pointer to it is a view, not a copy. Writing through that pointer is undefined behaviour: on a PC it crashes, on a microcontroller it may silently do nothing. The array form creates a private writable copy.

char *p = "Good";
p[0] = 'g';                   /* BUG: modifies read-only data */

char a[] = "Good";
a[0] = 'g';                   /* FIX: the array is your copy */

const char *q = "Good";       /* BEST for read-only use: the compiler enforces it */
FormWhere the characters liveCan you write?
char a[] = "Good";Array, usually RAMYes
const char *q = "Good";Read-only data, usually flashNo, and the compiler says so
char *p = "Good";Read-only dataCompiles, but writing is undefined behaviour

Mistake 3: Appending a Character With strcat

strcat joins two strings. The character '?' is a single small integer, not a string, so passing it makes the function treat the number 63 as an address and read from there. The fix is to pass the string "?", which is the two bytes ? and \0. Remember also that the destination must have enough room for both parts plus the terminator.

char msg[24] = "Ready";
strcat(msg, '?');      /* BUG: a char is not a string */
strcat(msg, "?");      /* FIX: a string literal */

Mistake 4: Assigning to an Array Name

An array name is not a variable that stores an address. It is the address of the first element, fixed for the lifetime of the array, so it cannot be the left side of an assignment. To put new text into an array, copy it with strcpy, snprintf or memcpy. Here is what a real compiler says:

char name[10];
name = "Asha";

bad_assign.c: In function 'main':
bad_assign.c:7:10: error: assignment to expression with array type
    7 |     name = "Asha";
      |          ^

The fix is snprintf(name, sizeof name, "%s", "Asha"); or strcpy when you have verified the length. The sizeof line in our fixed program below also shows the difference: a four letter array reports 5 bytes, the terminator included, while a pointer reports the size of an address, usually 8 on a 64-bit system.

Mistake 5: Returning the Address of a Local Array

A local array lives in the function’s stack frame. When the function returns, the frame is released and the next call may overwrite those bytes. A pointer to it becomes dangling. The program may even print the right text a few times, which makes the bug harder to find. There are three correct designs.

DesignWho owns the memoryTypical use
Caller passes a buffer and its sizeCallerBest default; no heap, thread safe
Function returns a heap blockCaller must freeWhen the size is unknown in advance
Function returns a pointer to a literal or static constNobody; it lives foreverFixed text such as error names
Why a returned local array dangles
call make_label→array created in stack frame→function returns→frame released→caller reads pointer→bytes may be overwritten

Mistake 6: Changing a Pointer Parameter and Expecting the Caller to See It

When you pass an array to a function, the function receives a pointer: a copy of the address. Assigning a new address to that parameter changes only the copy. The caller’s array is untouched. To change the array contents you must write through the pointer. To change which object a caller’s pointer refers to, you need a pointer to the pointer.

Two very different statements
x = “Jack”;
rebinds the local copycaller sees no change
strcpy(x, “Jill”);
writes into the shared arraycaller sees the new text

Mistake 7: Misreading Adjacent Literals and Line Continuation

Two string literals separated only by whitespace are joined by the compiler into one. That is a convenient way to write long messages, but a missing comma in an array of strings merges two entries silently and shifts every index after it. A backslash at the very end of a line continues a literal on the next line, and any spaces at the start of that next line become part of the string.

All the Fixes in One Program

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

/* Safe replacement for "return the local array": caller owns the buffer. */
static void make_label(char *dst, size_t cap, int id)
{
    snprintf(dst, cap, "node-%02d", id);
}

/* Rebinds only this function's private copy of the pointer. */
static void rebind_only(char *x)
{
    x = "Jack";
    (void)x;
}

/* Writes through the pointer, so the caller's array changes. */
static void write_through(char *x)
{
    strcpy(x, "Jill");
}

int main(void)
{
    char label[16];
    char writable[] = "good";       /* array: a private, writable copy */
    char msg[24] = "Ready";
    char arr[8] = "";
    const char *joined = "baud=" "115200" " parity=none";
    const char *folded = "part one, \
part two";

    make_label(label, sizeof label, 7);
    printf("label    : %s\n", label);

    writable[0] = 'G';
    printf("writable : %s\n", writable);

    strcat(msg, "?");               /* "?" is a string, '?' is not */
    printf("strcat   : %s\n", msg);

    printf("sizeof array=%zu, sizeof pointer=%zu\n",
           sizeof writable, sizeof joined);

    rebind_only(arr);
    printf("after rebind_only  : [%s]\n", arr);
    write_through(arr);
    printf("after write_through: [%s]\n", arr);

    printf("%s\n%s\n", joined, folded);
    return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o pitfalls_fixed pitfalls_fixed.c
./pitfalls_fixed
label    : node-07
writable : Good
strcat   : Ready?
sizeof array=5, sizeof pointer=8
after rebind_only  : []
after write_through: [Jill]
baud=115200 parity=none
part one, part two

Read the output against the code. The label comes from a caller-owned buffer, the writable array changed its first letter, strcat worked with a string, rebind_only left the array empty while write_through filled it, and both literal forms printed as one string.

Best Practices, Performance and Security

  • Compile with -Wall -Wextra -pedantic and treat warnings as errors; most mistakes above produce a warning.
  • Declare read-only text as const char * so writes are rejected at compile time.
  • Pass buffer sizes with every buffer. Prefer snprintf and memcpy with checked lengths over unbounded calls.
  • Initialise every pointer, to a valid object or to NULL, and test for NULL before use.
  • Run tools such as AddressSanitizer on a PC build of your firmware logic; it finds dangling pointers and overflows that hardware hides.
  • Many security vulnerabilities in the field are string bugs: overflowed buffers, missing terminators and unchecked lengths.

Quiz: Test Your Understanding

Try each question before you open the answer.

  1. What does char *s; create?
    Show answer

    A pointer variable only, with an indeterminate value. There is no text storage behind it.

  2. Which is safe to modify: char a[] = "ok"; or char *p = "ok";?
    Show answer

    The array. The pointer refers to a literal that may be in read-only memory.

  3. What is wrong with strcat(msg, '!');?
    Show answer

    A character is not a string. Use "!".

  4. Why is name = "Asha"; illegal for char name[10]?
    Show answer

    An array name is a fixed address, not an assignable variable. Copy the text in.

  5. Why is returning a local array dangerous?
    Show answer

    Its stack frame is released when the function returns, so the pointer dangles.

  6. Output of: char s[] = "embed"; s[2] = 'X'; puts(s);
    Show answer

    emXed

  7. Output of: char a[8] = "ab"; strcat(a, "cd"); printf("%zu %zu", strlen(a), sizeof a);
    Show answer

    4 8: the length is four, the array is eight bytes.

  8. Output of: printf("%s", "go" "al");
    Show answer

    goal, because adjacent literals are joined.

  9. A function does x = "hi"; on its char *x parameter. Does the caller’s array b[4] = "no" change?
    Show answer

    No. It prints no; only the local pointer copy was rebound.

  10. What are strlen(t) and sizeof t for char t[] = "ab\0cd";?
    Show answer

    2 and 6. strlen stops at the first zero byte; sizeof counts the whole array including the final terminator.

Embedded C Interview Questions on Strings

  1. What is the difference between char a[] and char *p for a string?
    Show answer

    The array owns writable storage and its name is a fixed address; the pointer is a variable that can point anywhere, including to read-only literal data. sizeof reports the array size for the first and the pointer size for the second.

  2. Why must a function that fills a buffer also receive its size?
    Show answer

    Because a pointer carries no length. Without the size the function cannot prevent overflow.

  3. Why is gets removed from the language?
    Show answer

    It cannot be told how large the buffer is, so any long input overflows it. Use fgets with sizeof.

  4. How would you implement strlen?
    Show answer

    Walk a pointer to the terminator and subtract the start address, returning size_t.

  5. What is the difference between memcpy and memmove?
    Show answer

    memmove handles overlapping regions; memcpy does not.

  6. Why might a string literal be placed in flash on a microcontroller?
    Show answer

    Literals are constant, so the toolchain keeps them in read-only memory to save RAM. That is why you declare pointers to them as const char *.

  7. How do you delete characters from a string in place?
    Show answer

    Use a read pointer and a write pointer, copy only the characters to keep, and write a new terminator.

  8. What does strcmp return, and why not use ==?
    Show answer

    It returns negative, zero or positive according to ordering of the first differing characters. The operator == compares addresses, not contents.

  9. What is a dangling pointer? Give a string example.
    Show answer

    A pointer to storage that no longer exists, such as the address of a local array returned from a function.

  10. How do you sort an array of strings cheaply?
    Show answer

    Keep an array of pointers and swap the pointers according to strcmp, instead of copying characters.

  11. What bugs does const prevent in string code?
    Show answer

    It turns accidental writes through pointers to read-only text into compile-time errors.

  12. How can a missing comma break a table of strings?
    Show answer

    Adjacent literals are concatenated, so two entries merge into one and every later index shifts by one.

Mini Challenge

Take any string function from the last six lectures and write three deliberately bad calls for it: a literal as the destination, a destination that is too small and a NULL pointer. Decide in advance what each should do, then make the function behave that way. That exercise is exactly what a code reviewer does.

Key Takeaways

  • A pointer needs real storage before any function writes through it.
  • Literals are read-only; use arrays to edit and const char * to read.
  • Pass strings, not characters, to strcat, and never assign to an array name.
  • Never return a local array; let the caller supply the buffer and its size.
  • Changing a pointer parameter affects only the local copy; writing through it affects the caller.

Conclusion

Every mistake in this lecture comes back to the same question: which memory does this pointer refer to, and who owns it? Once you answer that automatically, string bugs stop being mysterious. They become routine items on a code review checklist.

You have now finished this batch of the Strings chapter: counting, editing, trimming, encoding, sorting, tables and pitfalls, all with original examples you can compile and extend. Keep practising with the challenges, then continue the free embedded C course with the next chapter. If this helped you, share this free C programming course with a friend who is starting embedded C programming.

Frequently Asked Questions

Why does my C program crash when I change a string?

You are probably writing to a string literal through a char *. Copy the literal into a char array or use const char * and do not write.

Why can I not assign a string to a char array?

An array name is a fixed address and cannot be assigned. Copy with strcpy or snprintf.

What is wrong with returning a local array from a function?

The array is destroyed on return, leaving a dangling pointer. Let the caller provide the buffer.

Does changing a pointer parameter change the caller’s array?

No. The function holds a copy of the address. Write through the pointer to change the contents.

What does the compiler do with two adjacent string literals?

It joins them into one literal, which is convenient but hides a missing comma in a table of strings.

Where can I practise more C string questions for free?

This free embedded C course and its free C tutorial series offer more lectures with quizzes and interview questions.

Keep Going With the Free Embedded C Course

EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →