C - 从未分配给变量的函数返回的结构
问题描述:
尝试打印字符串时出现段错误。 这里是一些问题的上下文,我认为这是由于我以某种方式错误地传递了一个结构。 加载文件读取* file_path并将其作为文档结构返回,但是在int main()中sudo从来没有任何数据。我跑在gdb和DOC程序LOAD_FILE()里面有它内部的有效数据,但须藤(也是INT主文档结构()从未得到的数据是有一个原因?C - 从未分配给变量的函数返回的结构
#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和我使用编译它的COMAND上运行的程序
$ gcc main.c -o out
答
在你的程序中,错误,而不是检查NULL,你正在分配NULL to doc.string -
if(doc.string = NULL)
将其更改为 -
if(doc.string == NULL)
第1步:之后'FILE *文件=的fopen检查返回值(FILE_PATH, “R”);' –
,我建议你阅读[如何调试小程序(HTTPS: //ericlippert.com/2014/03/05/how-to-debug-small-programs/),并学习如何使用* debugger *逐行扫描代码。另请[请阅读如何提出良好问题](http://stackoverflow.com/help/how-to-ask),编辑您的问题,向我们展示您阅读的文件的内容以及预期的和实际的输出你的程序。 –
我注意到的一件事是,在'for(int i = doc.length; i