简体   繁体   English

C-从函数返回的结构未分配给变量

[英]C - struct returned from function not assigned to variable

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. 加载文件读取* file_path,并将其作为文档结构返回,但在int main()中,sudo从未包含任何数据。 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? 我在gdb中运行程序,并且load_file()内部的doc中包含有效数据,但是sudo(也是int main()中的文档结构从不获取数据。请问为什么吗?

#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 万一重要,我要在现代版本的Arch Linux和我用来编译它的comand上编译并运行该程序,

$ gcc main.c -o out

In your program, by mistake instead of checking for NULL, you are assigning NULL to doc.string - 在您的程序中,错误地是将NULL分配给doc.string而不是检查NULL-

if(doc.string = NULL)

Change it to - 更改为-

if(doc.string == NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM