c - 将动态结构传递给函数时出现段错误(核心转储)

标签 c function struct malloc

我正在尝试让它为我的作业工作,但我不断收到段错误错误,但我看不到问题。

struct line{
        int source;
        int dest;
        int type;
        int port;
        char data[51];
};


int main(){
    struct line *dataIn;
    dataIn = malloc(sizeof(struct line));
    int nRecords = 0;

    readFile(&nRecords, dataIn);

    int i=0;
    for(i = 0; 1 < 100; i++){
        printf("Source: %d Data: %s\n", dataIn[i].source, dataIn[i].data);
    }

    return 0;
}

void readFile(int *nRecords, struct line *dataIn){
    FILE *fileIn;
    fileIn =fopen("data.txt","r");
    if (!fileIn){
        puts("File Open Error");
        return 1;
    }
    while(fscanf(fileIn, "%d:%d:%d:%d:%[^\n]", &dataIn[*nRecords].source, &dataIn[*nRecords].dest, &dataIn[*nRecords].type, &dataIn[*nRecords].port, dataIn[*nRecords].data) == 5){
        nRecords++;
        dataIn = realloc(dataIn,(*nRecords+1)*sizeof(struct line));
    }
    fclose(fileIn);
}

此外,当我在顶部添加函数原型(prototype)时:

void readFile(int*, struct line*);

我收到错误:

Conflicting Types for 'readFile'

最佳答案

C 使用按值传递来传递函数参数。在您的代码中,dataIn 本身使用值传递方式传递给 readFile()

现在,dataIn本身就是一个指针,您可以从函数中更改dataIn的内容,但不能更改dataIn本身(查看函数中的 realloc()),并期望将其反射回 main()

因此,返回后,您的 dataIn 只有一个元素,因为它之前是 malloc() 的。然后,for 循环显然尝试访问超出范围的内存,创建 undefined behavior .

如果您想从函数中更改dataIn,则需要将指向它的指针传递给函数。

也就是说,

  • nRecords 是一个指针,nRecords++;不会更新相应的int 值。

  • void 函数 readFile() 不应包含带有 return 1;< 等值的 return 语句。/

关于c - 将动态结构传递给函数时出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781329/

相关文章:

c - main 中的 next 函数和数组的结果是什么?

c - 带有链表的无限循环

c++ - 我无法理解 C++ 中的结构声明

javascript - typeof 2D 数组将变为 String。为什么?

c结构问题

使用 clang 编译最小测试共享库

c - 如何在C中读取数字到字符串直到行尾

c++ - 为什么 clang 3.4 以如此奇怪的方式实现 `std::function`?

char * 在一个结构中,指向一个 char 数组,然后使用 strncpy。试图避免动态分配的内存

c - WinCE 应用程序的 Hello World(C 和 C++)- Visual Studio 2008