【问题标题】:free(): invalid next size (fast):free():下一个尺寸无效(快速):
【发布时间】:2014-08-26 18:32:09
【问题描述】:

在过去的一个小时里,我一直在为这个奇怪的错误而苦苦挣扎。代码已尽可能最小化,但在运行时仍然出现以下错误:

*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x0000000001823010 ***

这是我正在编译的。

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>

    void random_fill(unsigned int * to_fill, unsigned int len) {
        srand(time(NULL));
        for( unsigned int i = 0; i < len; i++) {
            to_fill[i] = (float)rand() / RAND_MAX * 100;
        }
    }


    #define SEQ_SIZE 2048
    int main(void) {
        printf("Sequence Size: %i\n", SEQ_SIZE);
        unsigned int * sequence = 0;
        sequence = (unsigned int *) calloc(0, sizeof(unsigned int) * SEQ_SIZE);

        random_fill(sequence, SEQ_SIZE);

        for(int i = 0; i < SEQ_SIZE; i++) {
            printf("%u ", sequence[i]);
        }
        printf("\n");

        free((void *)sequence);

        return 0;
    }

我用来编译代码的命令是gcc -std=c99 main.c,我的 gcc 版本是 4.4.7 20120313(在 Red Hat 4.4.7 上运行)。为了确认这不是 gcc 中的错误,我还使用 gcc 4.8.2 对其进行了编译,但仍然遇到相同的错误。最后,我编译了它并在我的笔记本电脑上运行它,它运行起来没有任何问题!

为什么会出现此错误?机器或我的操作系统有问题吗?

【问题讨论】:

  • 所以你(c)分配0sizeof(unsigned int) * SEQ_SIZE 元素?也许你应该calloc(SEQ_SIZE, sizeof(unsigned int))
  • 天哪,你的权利!我误读了文档并假设第一个参数是要分配的默认值。
  • 次要:不需要free((void *)sequence); 中的(void *) 演员。
  • 您应该使用gcc -Wall -g 编译并使用valgrind 以及gdb 调试器。

标签: c gcc free calloc


【解决方案1】:

正如 Petesh 在 cmets 中所说:

sequence = (unsigned int *) calloc(0, sizeof(unsigned int) * SEQ_SIZE);

该行将分配 0 个非零大小的元素。您可能正在寻找:

sequence = calloc(1, sizeof(unsigned int) * SEQ_SIZE);

这可行,但不能解决一些潜在的溢出问题。所以你实际上应该写:

sequence = calloc(SEQ_SIZE, sizeof(unsigned int));

或者,甚至更好:

sequence = calloc(SEQ_SIZE, sizeof(*sequence));

其他想法:

您应该只在给定程序中调用一次srand()。通常人们只是将其称为main() 中的第一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多