I get a segmentation fault when printing a dynamically allocated array. I'm not familiar with dynamically allocated arrays so this could be a problem. My program compiles fine if I comment out the for loop where I'm printing each element of the array. So I feel like my readText function is fine but I could be wrong. I've done research before asking this question and I can't find an answer. I just need to be able to print out each element of the text1 array. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int size1, size2;
FILE *fh1, *fh2;
if( argc<3 ) {
printf("need two file names\n"); return(1);
}
if(!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]); return(2);
}
if(!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]); return(3);
}
if(argc>3) {
if(!(fh3 = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]); return(4);
}
}
fseek(fh1, 0, SEEK_END);
size1 = ftell(fh1);//Getting fh1 size
fseek(fh1, 0, SEEK_SET);
fseek(fh2, 0, SEEK_END);
size2 = ftell(fh2);//Getting fh2 size
fseek(fh2, 0, SEEK_SET);
char* readText(int, FILE*);//declaring function
char *text1 = readText(size1, fh1);
int i;
for (i=0; i<size1; i++)
printf("text1[%d] = %s\n", i, text1[i]);
return 0;
}
char *readText(int size, FILE *fh)//reads file into a dynamically allocated array
{
char * text = malloc(size * sizeof(char));
int i=0;
while(!(feof(fh)))
{
fgets(text, size, fh);
++i;
}
return text;
}