bluewave41
bluewave41

Reputation: 145

C produces wrong results on 32 bit systems

The following code is supposed to take in a users input and write it into a file.

int main(int argc, char* argv[]) {
FILE* fp;
char string[512]; //maximum it should ever be
char first[19];
char last[19];
char grade[4];
char choice[7];
if(argc == 2)
    fp = fopen (strcat(argv[1],".txt"), "wb+");

while(fgets(string, 512, stdin) != NULL) {
    sscanf(string, "%s", choice);
    if(strcmp(choice, "add") == 0) {
        printf("%s\n", string); //print out what string is
        if(sscanf(string, "%s %s %s %s", choice, first, last, grade) == 4) {
                    printf("%s\n", choice);
                    printf("%s\n", first);
                    printf("%s\n", last);
                    printf("%s\n", grade);
                    addData(first, last, grade, fp, 0);
        }
    }

As a test I enter in: add test tester 100

Add data should put the information into the file.

void addData(char first[], char last[], char grade[], FILE* fp) {
    rewind(fp);
    spaces(first, last, grade);
    fprintf(fp, first);
    fprintf(fp, last);
    fprintf(fp, grade);
}

void spaces(char first[], char last[], char grade[]) {
size_t i;
    for(i=strlen(first);i<20;i++)
        first[i] = ' ';
    for(i=strlen(last);i<20;i++)
        last[i] =  ' ';
    for(i=strlen(grade);i<=4;i++)
        grade[i] = ' ';
    grade[strlen(grade)-1] = '\0'; }

When added into the file I expect to see:

test                tester              100

Instead I get:

 est                dd test tester 1000                   est                dd test tester 100100                   est                dd test tester 100

On a 64 bit system of course I get this:

test                tester              100

What exactly is going on, why is it printing a bunch of information to my text file I didn't ask for? How would I potentially fix this so it works on 32 and 64 bit systems?

Upvotes: 0

Views: 85

Answers (2)

bluewave41
bluewave41

Reputation: 145

As WhozCraig said, a bunch of my array sizes were wrong. I wasn't accounting for spaces when I set the sizes so the spaces were pushing it over the size I specified.

Upvotes: 0

Gopi
Gopi

Reputation: 19864

fgets(string, 512, stdin) != NULL

What you have is array out of bound access as the array string can hold just 44 characters but you are allowing to write more than 44 characters.So the behavior is undefined.

fgets(string, sizeof(string), stdin) != NULL

is what you should have

Upvotes: 2

Related Questions