Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program ?

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

int main()
{
    char str1[5], str2[5];
    int i;
    gets(str1);
    gets(str2);
    i = strcmp(str1, str2);
    printf("%d\n", i);
    return 0;
}

 

  • A.Unpredictable integer value
  • B.-1
  • C.Error

Answer: A

Correct answer: Unpredictable integer value

Two things make the result unpredictable. The buffers are only five bytes and gets() cannot limit what it reads, so any input of five characters or more overruns them. And even with short input, strcmp returns a value whose sign is defined but whose magnitude is not - some libraries return the difference of the first differing characters, others just -1, 0 or 1. Code should test the sign, never a specific number.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.