Recently I have been learning C from K&R's book, and then I came across an error. From what I know a segmentation fault is something to do with the memory, but it is not explained in the book. If you could please look at my code and explain what a segmentation fault is, and how this error came to be in my code. Thank you.
#include <stdio.h>
#define MAXLINE 256
int main () {
int c, ndigit[10], i, d, e;
char str[MAXLINE];
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9')
++ndigit[c - '0'];}
for (i = 0; i <= 9; i++) {
for (d = 0; d < ndigit[i]; d++)
str[d] = '*';
str[d] = '\0';
printf("%d: %s\n",i,str);
for (e = 0; e <= MAXLINE; e++)
str[e] = '\0';
}
return 0;
}
You aren't initializing
ndigit to zero, it's an array of garbage values that you then increment. It's likely
ndigit's values are quite large, causing you to access
str with a very large index, overflowing the bounds of the
str array into invalid memory regions. The operating system sees you trying to access invalid memory regions and issues a segmentation fault, killing your program.
Also, as Jean-François Fabre points out, your
for-loop should go to
< MAXLINE because the last valid index for
str is
MAXLINE - 1.
And as mszymborski points out, you likely want a newline (
'\n') at the end of your print statement.