Am noob, need assistance.
I am reading from a file into a char array and then trying to give that array to my custom function.
char *args[41];
FILE *f;
int hist = 0;
f = fopen("file.test", "a+");
while(fgets(*args, 40, f))
{ myFunction(hist, args);
hist++; }
Function:
void myFunction(int idx, char *args[])
{stuff}
The file exists and has several lines of text in it. fgets is seg faulting when I use the pointer array, however my function needs it that way for the rest of the program to work. The program works fine when not trying to read this file. Each line of the file should have no more than 40 characters. I believe fgets will read up to 40 characters and then also add a new line? I made the array size 41 just in case. Anyway, I also tried creating a normal char array but then myFunction won't accept it (and I can't easily change that function). What do?
fgets
is segfaulting because those pointers doesn't point to any valid memory. You were accessing an uninitialized pointer which is undefined behavior.(fgets
tries to write into the address provided to it as the first parameter and that is where it tries to access some illegal or not-permitted-to-access
memory resulting in seg-fault).
Allocate some memory it will not give segfault.
char *arg[41]
is an array of 41 char*
's , not array of char
's and those pointers don't point to any relevant memory.
#define LEN 100
for(size_t i = 0; i<41; i++)
arg[i] = malloc(sizeof *arg[i] *LEN);
if( arg[i] == NULL){
fprintf(stderr,"Error in malloc");
exit(1);
}
...
size_t i = 0;
while(fgets(args[i], 40, f)) //read into each of the character array
{
hist++;
i++;
}
myFunction(hist, args);
Now arg[i]
points to dynamically allocated memory unlike the previous case.
Don't forget to to free the dynamically allocated memory.
In case you want to pass each of the read string (null terminated char
array) to the function then the signature would be
void myFunction(int index,char* arg); //accessing the char array
In case you want to pass the whole array of char pointers then the signature would be
void myFunction(int index,char* args[]);