I'm trying to make a function that gets a dynamically allocated string from a file, ignoring leading whitespace and going until it reached whitespace again, but I keep get a "Segmentation fault (core dumped)" error. I tried using valgrind to find the cause and it says something about feof
Invalid read of size 4
==1155740== at 0x48EDE24: feof (feof.c:35)
==1155740== by 0x1095E7: my_string_extraction (my_string.c:73)
==1155740== by 0x109285: main (main.c:10)
==1155740== Address 0x0 is not stack'd, malloc'd or (recently) free'd
However, when I copy it over to visual studio it works with no problems
Function
Status my_string_extraction(MY_STRING hMy_string, FILE* fp)
{
char currCh;
int i = 0;
int x = 0;
int wordStart = 0;
struct My_string* temp = hMy_string;
char* tempData;
while (!feof(fp))
{
currCh = fgetc(fp);
if ((currCh == ' ' || currCh == '\n' || currCh == '\t' || feof(fp)) && wordStart != 0)
{
temp->data[i] = '\0';
temp->size = i - 1;
fseek(fp, -1, SEEK_CUR);
return SUCCESS;
} else if (currCh == ' ' || currCh == '\n' || currCh == '\t') {
} else {
if ((i+1) >= temp->cap)
{
tempData = (char*) malloc(sizeof(char) * temp->cap * 2);
for(x = 0; x < temp->size; x++)
{
tempData[x] = temp->data[x];
}
free(temp->data);
temp->data = tempData;
temp->cap = temp->cap * 2;
}
wordStart = 1;
temp->data[i] = currCh;
i++;
temp->size = i;
}
}
temp->data[i + 1] = '\0';
return FAILURE;
}
Main
#include <stdio.h>
#include <stdlib.h>
#include "my_string.h"
int main(int argc, char* argv[])
{
MY_STRING hMy_string = NULL;
FILE* fp;
hMy_string = my_string_init_default();
fp = fopen("Spring2019/COMP1020/HANGMAN/simple.txt", "r");
my_string_extraction(hMy_string, fp);
my_string_destroy(&hMy_string);
//fclose(fp);
return 0;
}