LearnFrenzy
Sign in Take a free test

Data Types · Find the Error · Question 3

strlen(s) - 1 with an empty string Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a bug. Which statement correctly describes it?

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

int count_spaces(const char *s) {
    int n = 0;
    for (size_t i = 0; i <= strlen(s) - 1; i++)
        if (s[i] == ' ')
            n++;
    return n;
}

int main(void) {
    printf("%d\n", count_spaces("a b"));
    printf("%d\n", count_spaces(""));
    return 0;
}
  • A strlen() cannot take an empty string
  • B n must be size_t
  • C There is no bug
  • D For "", strlen(s) - 1 is size_t 0 - 1 = SIZE_MAX, so the loop reads far beyond the string Correct
Correct Answer: Option D

size_t is unsigned, so 0 − 1 wraps to the largest value and the condition never fails. Write the loop as i < strlen(s) (better: store the length first), which needs no subtraction.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links