slavko
slavko

Reputation: 103

Memory overflow confusion in C

this part of the code is just a bit of a task I was solving in school. All I should do is open file oblici.txt and guess the figure inside (10x10 field consisting of # and - showing the figure). So, I misscalculated size of the string s and instead of 11 I allocated only 10 spaces. The problem is, it wont count over 2. Well, I found a solution (s[11] and it works) but cant figure out why is this a problem. Not just why is it a problem, I know overflow is not a good thing, but how in hell it can write 0 (instead of 9) when I have the if(b>0) which cleary eliminates the possibility of writing 0 inside the array x. My only guess was that '\0' has value of 0 and it gets written inside of b but that just doesnt make sense...

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

int main()
{
    FILE *fp=NULL;
    int x[10],i,j=0,b=0;
    char s[10];
    fp=fopen("c:\\temp\\oblici.txt","r");
    if (fp==NULL)
        exit(1);
    while(fscanf(fp,"%s",s)!=EOF){
        for(i=0;i<10;i++)
            if(s[i]=='-')
                b++;
        if(b>0)
            x[j++]=b;
        b=0;
    }
    for(i=0;i<j;i++)
        printf("%d ",x[i]);
    fclose(fp);
}

Where oblici.txt is:

enter image description here

Upvotes: 0

Views: 64

Answers (1)

thomsten
thomsten

Reputation: 46

It is because there is a newline (\n) character at the end of each line, thus in total 11 characters per line. Using 10 messes up the calculation.

As a tip, btw, avoid not using {} around if, for and while statements as it is a really common way to introduce bugs!

Upvotes: 3

Related Questions