I'm reading a file char by char. When I reach a colon I want to skip past all characters until I reach a newline character. Effectively, after seeing a colon I wish to skip to the next line (if another line exists). Seems simple enough, but I'm receiving a sigsegv when I try to break out of my second while loop which skips over the data I don't care about.
Without the break the code behaves as I would expect it to (although not my desired output). That is, it reads data until the first colon, then it will skip to EOF and exit.
5 FILE *fp = fopen("myFile", "r");
6 char *string = (char*) malloc(sizeof(char));
7 char *head = string;
8 if( fp ){
9 int c;
10 while( (c=fgetc(fp)) != EOF ){
11 if(c == ':'){
12 *string++ = '\n';
13 while( (c=fgetc(fp)) != EOF ){
14 if( c == '\n' ) // Skip to end of line
15 break; //removing break avoids sigsegv
16 }
17 }else{
18 *string++ = c;
19 }
20 }
21 }
It seems that when I break out of the loop, either c or fp are modified somehow that cause a sigsegv. My best guess is that fp is somehow modified and generates this error when the parent fgetc() calls on fp. Beyond that, though, I'm not sure what's causing the issue.
You need to allocate more bytes for
string. This line:is only allocating one byte for your string.