gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:45 25 4
gpt4 key购买 nike

我在尝试打印字符串时遇到段错误。这是问题的一些背景,我认为这是由于我以某种方式错误地传递了一个结构。加载文件读取 *file_path 并将其作为文档结构返回,但在 int main() sudo 中从来没有任何数据。我在 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;
}

如果重要的话,我正在现代版本的 Arch Linux 上编译和运行程序,我用来编译它的命令是

$ gcc main.c -o out

最佳答案

在您的程序中,您错误地没有检查 NULL,而是将 NULL 分配给 doc.string -

if(doc.string = NULL)

改成-

if(doc.string == NULL)

关于C - 从未分配给变量的函数返回的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46591039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com