Reputation: 1
I am getting a segfault when trying to print a string. here is some context for the problem, I think that it is due to me somehow passing a struct incorrectly. Load file reads *file_path and it returns it as a document struct, but in int main() sudo never has any data in it. I run the program in gdb and doc inside of load_file() has valid data inside of it, but sudo (also a document struct in int main() never gets the data. Is there a reason why?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
const char *sudoers_path = "thing";
char *read_string = "sandos";
int read_string_len = 6;
struct document{
char *string;
int length;
};
struct document sudoers;
struct document loadfile(char *file_path){
char char_temp[2] = "1";
struct document doc;
int temp=0;
FILE *file = fopen(file_path,"r");
doc.string = (char *)malloc(10*sizeof(*doc.string));
doc.length=10;
int len_doc_read = 0;
while(temp != EOF){
temp = fgetc(file);
if(temp == EOF){
break;
}
char_temp[0] = (char) temp;
if(doc.length - len_doc_read==0){
doc.string = (char *)realloc(doc.string, (doc.length+10)*sizeof(*doc.string));
for(int i = doc.length; i< len_doc_read-2; i++)
doc.string[i]=' ';
doc.string[doc.length-1] = '\0';
}
len_doc_read++;
strcat(doc.string, char_temp);
strcat(doc.string, "\0");
doc.length++;
}
//I am the cracker of C, destroyer of programming! --me
if(doc.string = NULL)
printf("memory failed");
return doc;
}
int main(){
struct document sudo = loadfile(sudoers_path);
struct document sand_find;
sand_find.string = "sandos";
sand_find.length = 7;
puts(sudo.string);
return 0;
}
Incase it matters I am compiling and running the program on a modern version of Arch Linux and the comand that I am using to compile it is
$ gcc main.c -o out
Upvotes: 0
Views: 70
Reputation: 12679
In your program, by mistake instead of checking for NULL, you are assigning NULL to doc.string -
if(doc.string = NULL)
Change it to -
if(doc.string == NULL)
Upvotes: 3