bastel bastel - 2 months ago 19
C Question

Segmentation fault, fgets in while loop

I try to read in a file multiple times instead of just once.
While trying that I got alot of segementation faults. The part of the program with the while loop looks like this:

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

/* General use buffer */
#define STRLEN 8196
char string[STRLEN];


int lines = 1024;
char **line;
int linemax;

int longest=0;


int main(){
int len,i;
int zwei = 1;
FILE * fp;
char *s;
int debug = 0;
line=(char **)malloc(sizeof(char *) * 1024);
do{
if ( (fp = fopen("rhel7_160731_0606.nmon", "r")) == NULL) {
perror("failed to open file");

perror("fopen");
exit(75);
}
printf("where is the problem1,3\n");
for (i = 0; fgets(string, STRLEN, fp) != NULL; i++) {
if (i >= lines) {
lines += 1024;
line = (char **)realloc((void *)line, sizeof(char *) * lines);
}

if (string[strlen(string)-1] == '\n')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == '\r')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == ' ')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == ',')
string[strlen(string)-1] = 0;
len = strlen(string) + 1;

if (len > longest)
longest = len;
s = malloc(len);
strcpy(s, string);
line[i] = (char *)s;
}
linemax = i;
lines = i;

if (debug)
for (i = 0; i < linemax; i++)
printf("line %d lastline %s\n", i, line[i-1]);

zwei++;

}while(zwei<4);

return 0;
}


It hangs nothing or ends with a segmentation fault.

Answer

You seem to have forgotten to allocate memory for line. It fails here: line[i] = (char *)s. I think you need to set lines to zero, since you reallocate line only if your iterator i gets grower than lines.

Also, fix this: while(zwei > 4) to while(zwei < 4). And, you need to free the memory you allocate - because you store all the pointers in line, it is not going to be complicated - just one loop.