【问题标题】:Malloc with a struct array带有结构数组的 Malloc
【发布时间】:2016-02-26 09:30:45
【问题描述】:

我正在尝试创建一个动态分配的结构类型数组,但遇到了一些问题。即程序在程序结束时在 fclose 命令处崩溃。在注释掉这一行之后,程序在返回 0 时崩溃,所以我假设我的文件 I/O 编码存在一些问题,并且我的内存分配也存在问题。我的目标是用文本文件中的值填充结构主机中包含的值。代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include <assert.h>
#include <stdlib.h>

typedef struct host_struct {
    int x, y, z, w;
    char os[8];
} host;


int main(void)
{
    host *ipArray = NULL;
    int numOfIps = 0;
    char tempFileCharVal = 'a';
    char fileString[8];
    int test;
    int i;
    int j;
    int k;
FILE *hostFile;

    hostFile = fopen("hosts.txt", "r");

    while (fscanf(hostFile, "%c", &tempFileCharVal) != EOF)      //Nested loops to find number of ips, relies on there being a new line at the end of each IP address.
    {
        if (tempFileCharVal == '\n')
        {
            numOfIps++;
        }
    }

    ipArray = malloc(numOfIps * sizeof(*ipArray));                    //Allocates memory to array of ip addresses based on number of IP addresses and size of type host.


    fclose(hostFile);                                   //Reset hostFile to beginning of file.
    hostFile = fopen("hosts.txt", "r");


    for (i = 0; i < (numOfIps); i++)                  //Iterate through IPs, values within IPs, and values within hostFile to assign values to ipArray.
    {
        for (j = 0; j < 5; j++)
        {
            for (k = 0; fscanf(hostFile, "%c", &tempFileCharVal) != '.'; k++)  //?? doesn't end loop if tempFileCharVal = '.'
            {
                if ((tempFileCharVal == ' ' || tempFileCharVal == '\n' || tempFileCharVal == '.') & j != 0) //?? Had to add this if statement to compensate for strange loop behavior.
                {
                    break;
                }
                if ((j == 0) & tempFileCharVal == '\n')
                {
                    fscanf(hostFile, "%c", &tempFileCharVal);
                }
                if ((j == 0) & (tempFileCharVal == '.' || tempFileCharVal == EOF))
                {
                    break;
                }
                fileString[k] = tempFileCharVal;
            }
            fileString[k] = '\0';
            switch (j)
            {
            case 0:
                ipArray[i].x = atoi(fileString);
                break;
            case 1:
                ipArray[i].y = atoi(fileString);
                break;
            case 2:
                ipArray[i].z = atoi(fileString);
                break;
            case 3:
                ipArray[i].w = atoi(fileString);
                break;
            case 4:
                strcpy(ipArray[i].os, fileString);
                ipArray[i].os[k] = '\0';
                break;
            }

        }
    }
    //fclose(hostFile);
    free(ipArray);
    return(0);

}

【问题讨论】:

  • sizeof(ipArray) 是指针的大小,因为ipArray 是指针。
  • 解决了吗?我想我应该重新发布它作为答案:P
  • Aaaaand,修复了它,一段时间以来一直在强调那个。再次感谢。
  • tempFileCharVal == EOF 是一个错误。 EOFint,不能安全地存储在 char 中。事实上,你从来没有尝试在角色中存储EOF,所以这个测试没有意义。
  • fscanf(hostFile, "%c", &amp;tempFileCharVal) != '.' 是一个错误:fscanf的返回值是成功读取的项目数,或者EOF。不会是 . 。在所有情况下,最好检查 fscanf(...) == 1 ,或者甚至更好,使用 fgetc 而不是 fscanf

标签: c arrays dynamic struct malloc


【解决方案1】:

这行你要小心:

ipArray = malloc(numOfIps * sizeof(*ipArray)); 

'ipArray' 是指针类型!不过,您需要更多的内存。正确的做法是这样写:

ipArray = malloc(numOfIps * sizeof(struct host_struct)); 

编辑:我现在看到之前有人对此发表过评论,看来我迟到了,对不起! ;-)

编辑:我错了,希望我没有混淆任何人!

【讨论】:

  • 菲尔,malloc 电话很好。 sizeof (*ipArray)sizeof ( 取消引用的指针 ),这与sizeof(struct host_struct)完全相同。解决这个问题,我将删除反对票。 (但是,解决这个问题并且答案的其余部分非常薄,所以最好删除,我将删除反对票)。如果您对此有任何疑问,请告诉我,我很乐意进一步解释。
  • @DavidC.Rankin 感谢您指出这一点!我很清楚,现在我又看了一遍。我不知道这会起作用
  • 很公平 - 我们都会偶尔发生这种情况。我发现乌鸦的味道最好加少许盐... do to others 的格言是什么?我希望 SO 上的更多人有诚信以这种方式处理反对票。我想我们每个人都可以做一个榜样。
  • 对@Phil 批评的优雅回应。这是最好的学习方式。干得好。
  • @DavidC.Rankin 谢谢。对于您处理和解释您的反对票的方式,我也必须为您提供支持。是批评/纠正的更好例子之一!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 2011-07-24
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多