Strange error in C

Asked

Viewed 63 times

0

Does anyone know why the value of i change in condition else if(i==721)? It changes strangely, as you can see in video of debuging.

teamfile=fopen("team.txt", "r");
if(fgets(c, 3, teamfile)==NULL){
    printf("Please add one team at least before try to add players or managers.\n");
}
else{
    playerfile=fopen("player.txt", "r");
    for(i=1; i<=722; i++){
        if(fgets(c, 250, playerfile)==NULL && i<720){
            do{                     //NAME
                printf("Name: ");
                getchar();
                gets(c);
                w=0;
                for(j=0; j<49; j++){        //<49 supondo que, para o string máximo, o c[49]=\0
                    if(c[i]>32 && c[i]<65){
                        w=1;
                        printf("Invalid characters. Try again. \n"); break;
                    }
                }                                                   
            }while(w==1);
            strcpy(player[i].name, c);

            do{                 //BIRTH DATE
                w=0;
                printf("Player birth date (dd mm yyyy): ");
                scanf("%i %i %i", &d, &m, &y); 
                w=dateverific(d, m,y);
            }while(w==1);
            player[i].birth.day=d;
            player[i].birth.month=m;
            player[i].birth.year=y;

            nations(i);     //NATION
            positions(i);       //POSITION
            teamlists(i, a);        //TEAM
            fclose(playerfile); 
            playerfile=fopen("player.txt", "a");
            fprintf(playerfile, "%s %d %33s %d %d %d %s %s\n", player[i].position, i, player[i].team, player[i].birth.day, player[i].birth.month, player[i].birth.year, player[i].nation, player[i].name); // explicar troca de id pela position realacianado com o fscafn do string clube name
            fclose(playerfile);
            break;
        }
        else if(i==721){
            printf("Impossible to add more players, all team are full.");
        }
        else{
        }
    }
}
  • How your variable was declared i?

  • Usually, int i=1;

1 answer

0


As you can see in the video itself, the value of i is overwritten with garbage before the line with the if that you put in question - and yes in the very line that contains if(fgets(c, 250, playerfile)==NULL && i<720). As the comparison i < 720 does not change the value of i, what "leftover" is that what is putting garbage in i is the call to fgets. This is a safe function, but it has to be used in the right way. In particular, the buffer parameter to which your data will be read, has to contain free memory - that is, your c has or has been declared with char c[250];, or have been declared as a pointer and pointed to an allocated memory region - something like char *c; ...; c = malloc(250); if (c==NULL) {exit(1); /* falha ao alocar memoria */}

The error probably happens because you are assuming that fgets allocates memory alone - which does not happen - in my system here (which is Posix-conformant), the description of the function is:

fgets(s) reads in at Most one Less than size characters from stream and Stores them into the buffer pointed to by s.

That is - the space pointed by the pointer that goes in the first parameter of the call you already have that is reserved.

Good - that’s the answer - I leave two additional tips:

(1) when asking questions at all times include a version of your full program that can replicate the error. In this case, for example, the problem is in the variable declaration c and on its not booting - but seeing only the chunk of code that you put in, there’s no way to know that. I could only understand what happens because of the debug video, but this is not to be necessary - just see the other questions of the site. When I say "version" - I mean you don’t need - and in general shouldn’t - put your original program full, but yes, take your program, and delete everything that isn’t related to the problem, but keep a chunk compilable and presenting the same problem that motivated the question.

(2) òtimo - you have learned to program in C, and manipulate files, and are trying to create a real program for "real" use. Except C is one of the last languages you should use for this. Being a relatively low level programming language, you have to worry about details like - allocating memory to each use of string to do, use functions designed in the 70’s to manipulate strings, which require error code checking on each call, functions that are dangerous due to non-data length checking - (legal, you are using fgets instead of fget - but you’re using scanf simple, that with a malicious typing can give segfault in your program, for example).

For applications of this type - which involve input and output of text, manipulation of text files, your application will be about 30 times simpler (no exaggeration, and about 3 times less code, at least), if you do it in a high-level dynamic language - languages like Python, Javascript, Ruby or PHP - for example. In all of these, the allocation of strings as internal objects is automatic, text files are read line by line, no memory worry, and there are very practical built-in functions to manipulate strings and check their content.

I suggest the Python language, although this might be a bit to the taste of the customer - but seriously: if you follow for 3 hours any tutorial (in text format) of Python, should be enough for you to re-write your application as it is in that language and continue the development from there. If you can read in English, I really recommend official language tutorial. Otherwise, in google appear several options in English.

Please understand that this is not a "tantrum" against C - language remains possibly the most important in the entire computing universe - and it has niches where it’s vital, for example, Iot - but it’s not the best tool for the kind of program you’re trying to do there, nor is gentle with programmers even at intermediate level.

  • Thank you very much, it’s settled!

  • If you solved your problem, you can mark the answer as "accepted".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.