this code gives an instant seg fault,I tried placing printf’s all over, I even tried to printf something just after the int=0; line but no matter what I did, it does not print anything but a segmentation fault. The file exists, also its location is the same with where I do the execution.
The file includes city names, one name on each line, nothing else, how do I read them and store them in an array :/
what if there was a number after each city, would the reading still be the same?
NewYork 5
LosAngeles 12
California 7
and the code;
int i=0;
char **city_names = malloc(sizeof(char*));
FILE* fp;
fp = fopen("abc.txt","r");
while(!feof(fp)){
city_names[i] = realloc(city_names[i],sizeof(char)*255);
fscanf(fp,"%s",city_names[i]);
i++;
}
fclose(fp);
You are only allocating a single char * of memory in your malloc then accessing beyond it in the while loop.
If you are going to do a 2D
mallocarray, you need tomalloceach pointer, thenmallocassign amallocinto each to the max string size (yuck).Or do something like
char city_name[3][256]instead to get it up and running.I’d also like to add that this sort of reading is very unsafe. You are reading an unknown amount of bytes into a fixed buffer size. If the string you read in were more than 255 bytes, you will destroy memory. You’d be better off using an
fread()into a fixed size buffer type solution (orftell()then file and read it all in at once for best efficiency) and then do your reading off the buffer. Not to mention all the overhead ofmallocandrealloc(they do add up).