0
嘗試打印字符串時出現段錯誤。 這裏是一些問題的上下文,我認爲這是由於我以某種方式錯誤地傳遞了一個結構。 加載文件讀取* 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
第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