-1

I will omit the whole code but these tests so far can be quite disturbing:

This get Accepted with ANSI C, C++ and C++ 11

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int p, q, r, s, t, u;
    char* str = malloc(1000);
    while(gets(str) != NULL) {
        sscanf(str, "%d %d %d %d %d %d", &p, &q, &r, &s, &t, &u);
        printf("%d %d %d %d %d %d\n", p, q, r, s, t, u);
    }
}

The disturbing fact comes now, this code get Runtime Error in ANSI C but Accepted in C++ and C++ 11:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int p, q, r, s, t, u;
    //== 6 instead of != EOF also gives me a runtime error
    while(scanf("%d %d %d %d %d %d", &p, &q, &r, &s, &t, &u) != EOF) {
        printf("%d %d %d %d %d %d\n", p, q, r, s, t, u);
    }
}
Gabriel Garcia
  • 584
  • 8
  • 13

1 Answers1

2

You forgot to return 0; - in C this means that main() returns a garbage status to the shell. In C++ omitting the return 0; is allowed, and a default status of 0 (== EXIT_SUCCESS) will be returned. In C however both of your programs will return an undefined status. In the first case you happen to get lucky and 0 is returned. In the second case something other than 0 is being returned (probably -1). Try and get into the habit of always returning a valid status from main regardless of whether you're working with C or C++.

See this excellent question and answer for further details.

Note also that compiling with warnings enabled (e.g. gcc -Wall ...) would have alerted you to this mistake immediately and saved you some time.

Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • could you explain better, why with the gets don't returned garbage status? – Gabriel Garcia Apr 13 '15 at 21:21
  • Did you read the linked answer (especially the penultimate paragraph) ? – Paul R Apr 13 '15 at 21:23
  • I know just fine how shell works but can't understand why it works with gets and not scanf – Gabriel Garcia Apr 13 '15 at 21:25
  • The return status is undefined for C in both cases - in the first case you happen to get lucky and 0 is returned. In the second case something other than 0 is being returned (probably -1). Try and get into the habit of always returning a valid status from main regardless of whether you're working with C or C++. – Paul R Apr 13 '15 at 21:27
  • So probably its assembly linked and some stack position or register sticks with another value than 0 and is returned if the last command is scanf, looks great, now, add this to your answer to make it perfect, thanks, this was an eye error indeed. – Gabriel Garcia Apr 13 '15 at 21:29