简体   繁体   中英

Segmentation error while printing a histogram

Ok so I wanted to do this question :"Write a program to print a histogram of the lengths of words in its input"(Exercise 1-13 of the book C programming by Brian and dennis ritchie). In this code I am printing only the tally of various word lengths(as its my first attempt).

This program compiles fine but while running the code I am getting this Segmentation fault(code dump) error. What's wrong with this code?

#include<stdio.h>
void read(char input[]);
void draw(int i[]);
main()
{
    int i,k,l;
    int len[16];
    char input[100];
    read(input);
    i=k=l=0;
    for(l=0;l<=15;l++)
    {
        len[l]=0;
    }
    while(input[i]!='/0')
    {   
        if(input[i]!='\n'&&input[i]!='\t'&&input[i]!=' ')
        {   k++;
            i++;
        }
        else
        {   len[k]=len[k]+1;
            k=0;
            i++;    
        }
    }
    draw(len);
    return 0;
}

void read(char c[])
{
    int i=0;
    int a;
    while((a=getchar())!=EOF)
    {   c[i]=a;
        i++;
    }
    c[i]='\0';
}

void draw(int len[])
{   int i=0;
    printf("Length\tWords\n");
    for(i=1;i<=15;i++)
    printf("%6d\t%6d\n",i,len[i]);
}
for(l=0;l<=15;l++)
{
    len[l]=0;
}

Your array is of type int [15] so you are accessing an element outside the array.

You have the exact same issue in the draw function here:

for(i=1;i<=15;i++)

Also:

char a;
while((a=getchar())!=EOF)

a should be of type int and not char . See this for the explanation:

http://c-faq.com/stdio/getcharc.html

one error i could notice is in for(l=0;l<=15;l++) . it should be for(l=0;l<15;l++) .

int len[15] means len is int array of size 15 with valid locations as len[0], len[1], ... len[14] but here you are accessing len[15] which is undefined and may cause segmentation fault .

In the function read , you do not check the length of the input, so if your input is larger than the number of entries in c you will write in memory not belonging to you.

Edit:

After you checked in a debugger it's easier to search for the reason of the error, and if you look at that while loop you will see it quite clearly:

while(input[i]!='/0')

You compare a character in input against an illegal character literal. You are using forward slash, but it should be a backward slash: '\\0' . Actually, your should give a warning about a multi-character character literal.

This line contains an error:

while(input[i]!='/0')

and causes your code to access memory not owned by your program.

It should be:

while(input[i]!='\0')

as the string terminating char is '\\0'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM