【问题标题】:C - struct returned from function not assigned to variableC - 从未分配给变量的函数返回的结构
【发布时间】:2017-10-05 16:55:09
【问题描述】:

尝试打印字符串时出现段错误。 这是问题的一些背景,我认为这是由于我以某种方式错误地传递了一个结构。 加载文件读取 *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

【问题讨论】:

  • 第一步:查看FILE *file = fopen(file_path,"r");之后的返回值
  • 我建议您阅读 Eric Lippert 的 How to debug small programs,并了解如何使用 调试器 逐行执行您的代码。也请read about how to ask good questions,并编辑您的问题,向我们展示您阅读的文件的内容,以及您的程序的预期和实际输出。
  • 我注意到的一件事是,在for(int i = doc.length; i&lt; len_doc_read-2; i++) doc.string[i]=' '; 之后,你用doc.string[doc.length-1] = '\0'; 截断它,所以删除了刚刚完成的任何空格填充。当doc.length == 0 时会发生什么?
  • 该语句将 NULL 分配给 doc.string - if(doc.string = NULL)。将其更改为 if(doc.string == NULL)。
  • 将 -Wall 添加到您的构建命令行。清除所有警告。

标签: c struct


【解决方案1】:

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

if(doc.string = NULL)

改成-

if(doc.string == NULL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2021-03-04
    • 2017-04-23
    • 1970-01-01
    • 2019-08-21
    • 2019-07-03
    相关资源
    最近更新 更多