📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following C code: #include

    #include int main() {     char str1[] = "Hello";     char str2[] = {'W', 'o', 'r', 'l', 'd', '\0', 'X'};     char str3[] = {'C', 'o', 'd', 'e'}; // No null terminator     printf("%zu %zu\n", strlen(str1), strlen(str2));     // What happens if strlen(str3) is called?     // printf("%zu\n", strlen(str3));     return 0; } What will be the output of the printf statement, and what would be the behavior if strlen(str3) were uncommented and executed?
    A 5 5; strlen(str3) would print 4. Correct Answer Incorrect Answer
    B 5 5; strlen(str3) would cause a segmentation fault or print a garbage value. Correct Answer Incorrect Answer
    C 5 6; strlen(str3) would print 4. Correct Answer Incorrect Answer
    D 5 6; strlen(str3) would cause a segmentation fault or print a garbage value. Correct Answer Incorrect Answer
    E 5 7; strlen(str3) would print 4. Correct Answer Incorrect Answer

    Solution

    Correct Answer: B (strlen(str1) is 5. strlen(str2) counts up to the first \0, so 5. strlen(str3) would read past the allocated memory until it finds a \0, leading to undefined behavior (segmentation fault or garbage value).)

    Practice Next
    ask-question