【问题标题】:Card game issues - memory and odd values纸牌游戏问题 - 内存和奇数值
【发布时间】:2013-05-12 16:07:03
【问题描述】:

我得到了大部分的工作,包括随机化和洗牌,但在分配正确的面/西装值时,我无法正确处理。另外,我正在“中止(核心转储)”,可能是因为我几乎不知道我在用 malloc 做什么(如果有的话,在这种情况下)。

typedef struct cards {
    char suits[4][9], faces[13][6];
    int suit, face, card;
} cards;

const int SHOE_SIZE = DECK_SIZE * numberOfDecks; // user given input, please disregard

cards shoe[SHOE_SIZE];
init_struct(&shoe);

cards *shoe_p = malloc(sizeof(cards) + 1000 * sizeof(int));
shoe_p = shoe;

int i;
for (i = 0; i < SHOE_SIZE; i++) {
    shoe[i].card = i;
    shoe[i].suit = shoe[i].card % 4;  // maybe one of these should be % and another /
    shoe[i].face = shoe[i].card % 13; // but when I try that, I get strings like "ace of ace"
    printf("card #%d = %s of %s\n", i+1, shoe->faces[shoe[i].face], shoe->suits[shoe[i].suit]);
}

free(shoe);

我遗漏的代码部分无疑是所描述问题的根源。如果我应该提供更多信息,请告诉我!

编辑:附加问题;我是否以适当的方式访问我的结构成员“面孔”和“西装”?对我来说似乎是这样,但话又说回来,我看不出还有什么会导致我的字符串输出奇怪(参见代码中的注释)。

另外,我可以将 SHOE_SIZE 作为我的数组的成员,并以相同的方式(shoe->variable)访问它,而不必先通过变量 SHOE_SIZE 分配它吗?

【问题讨论】:

    标签: c pointers segmentation-fault malloc


    【解决方案1】:
    cards *shoe_p = malloc(sizeof(cards) + 1000 * sizeof(int));
    shoe_p = shoe;
    

    这里您正在泄漏内存:shoe_p 指向了一些未分配的内存,但现在您丢失了该指针,因为您将它重新分配给指向 shoe 的第一个元素的指针。我认为你根本不需要这两行。

    free(shoe);
    

    也是错误的:你没有使用malloc()创建shoe,所以你不需要也绝对不能free()它。

    可能是因为我几乎不知道我在用 malloc 做什么

    没错,但别担心:你可以通过阅读this来提高你的知识。

    【讨论】:

    • 如何使用 malloc 创建鞋子?
    • @kensing shoe = malloc(sizeof(cards) * SHOE_SIZE);
    • @Magtheridon96 谢谢,我经常使用那个新词 ;)
    • 错误:从类型 'void *' 分配给类型 'struct cards[(unsigned int)SHOE_SIZE]' 时不兼容的类型我还没有能够成功使用 malloc()除了指针之外的任何东西.. (unsigned int) 来自哪里?
    • @kensing 您不需要将shoe 定义为数组。您将其声明为指向card:card *shoe = malloc(...); 的指针。或者如果你已经将它定义为一个数组,那你为什么还要使用malloc()呢?
    【解决方案2】:
    const int SHOE_SIZE = DECK_SIZE * numberOfDecks;
    cards shoe[SHOE_SIZE];
    

    这些行根本没有意义。第一行在运行时计算(即使作为用户给定的输入)一个常数。所以在编译它的值时还不知道。但是在下一行中,您将使用这个未知数在编译时分配非动态内存。因此,如果您想正确执行此操作,请将第二行扔掉并使用malloc()(正如您在下面几行中所做的那样)。此外,您将使用 shoe_p = shoe; 行丢弃此内存。解决这个问题的正确方法是:

    ...
    const int SHOE_SIZE = DECK_SIZE * numberOfDecks;
    cards *shoe = malloc(sizeof(cards) + 1000 * sizeof(int));
    init_struct(&shoe);
    
    int i;
    ...
    

    而且因为您使用的是malloc(),所以free() 绝对正确。

    【讨论】:

    • 有价值的输入,但是我仍然遇到分段错误
    • 正如我在这一刻注意到的那样,您的malloc() 电话也没有任何意义。一定是malloc(sizeof(cards) * 1000); 还是我理解你的源代码有问题?
    • 我只是确保肯定绰绰有余,但现在是malloc(sizeof(card) * SHOE_SIZE);
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多