c - Segmentation fault using arrays -
well, i've been @ forever , know fault is, no clue how fix it. know fgets , scanf better program, can't that.
the program worked 10 minutes ago, changed , got seg fault. changed , still got seg fault. anyway, i'm sure fresh eyes see right away. have @ :d
ps: please note (lessthan) instead of < because don't know how leave in code examples still :(
#define wordlength 15 #define maxline 1000 int main() { char *line[maxline]; int = 0; int j; int n; char c; (n=0; c!=eof; n++){ char *tmp = (char *) malloc(sizeof(char)*wordlength); while ((c=getchar())!=' ') tmp[i++]=c; line[n]=tmp; i=0; printf("\n%s\n",line[n]); // } for(j = 0; j < n; j++){ printf("\n%s\n", line[j]); free (line[j]); } return 0; }
you doing line[n++] = tmp
. , accessing line[n]
after that. line[n]
hasn't been assigned.
to change it, can print line[n-1]
instead, clearer be:
line[n] = tmp; = 0; printf(... line[n]);
and place increment in statement instead i.e. for (n = 0; c != eof; n++)
.
edit
this summary of do:
place i=0
assignment @ start of loop. logically, initialization of i
, done in 2 places (at int = 0;
, after assignment of line[n]
). both places not near 1 expect initialization of variable used in while
loop be.
guard against nonsense input checking i
not exceed wordlength-1
. actually, code inner while
loop for
loop on so:
for (i = 0; < wordlength; i++) { tmp[i] = getchar(); if (tmp[i] == ' ') break; } tmp[i] = 0;
or (in character) for(i = 0; < wordlength; ++i) if ((tmp[i] = getchar()) == ' ') break;
followed by..
tmp[i] = 0
nul-terminate string. since malloc
doesn't return 0-filled memory block.
Comments
Post a Comment