2

我创建了一个二维数组,但失败了,我得到“lab10.exe 中 0x77a415de 处的未处理异常:0xC0000374:堆已损坏。” 不知道从这里去哪里或如何调试。我相信这与我的数组大小或使用 malloc() 有关。非常感谢您提前提供的帮助!

//Get the number of Columns from the user
printf("Enter the number of rows and columns:\n");
scanf("%d", &dimension);

//Allocate 1-D Array of Pointers, Array 'a'
a = (int** ) malloc( sizeof(int)*dimension);
if(a == NULL)
{
    printf("\nError Allocating Memory");
    exit(1);
}

//Allocate Rows for 2-D Array; Array 'a'
for(r = 0; r < dimension; r++)
{
    a[r] = (int*) malloc( sizeof(int) * dimension);
    if (a[r] == NULL)
    {
        for(i = 0; i< r; i++)
            free(a[i]);
        printf("\nError Allocating Memory");
        exit(1);
    }
}

还有更多,但我从相同的整数“维度”执行了 4 次不同的操作。谢谢!

4

5 回答 5

2

第一的:

a = (int** ) malloc( sizeof(int)*dimension);

您正在分配指针数组,因此您想要:

a = (int** ) malloc( sizeof(int*)*dimension);

int 和 int* 的大小不保证是一样的!

第二:

if (a[r] == NULL)
{
    for(i = 0; i< r; i++)
        free(a[i]);
    printf("\nError Allocating Memory");
    exit(1);
}

你释放所有行的内存,但你不释放“a”本身的内存。

于 2012-11-08T21:11:29.913 回答
2

这一行是错误的:

a = (int** ) malloc( sizeof(int)*dimension);

dimension为 type 的元素数组分配了足够的空间int,但随后您将其用作int*. 如果您正在编译 64 位程序,sizeof(int*)则为 8 但sizeof(int)为 4,因此您没有分配足够的空间。您需要使用sizeof(int*)

a = (int** ) malloc( sizeof(int*)*dimension);
//                          ^^^^^
于 2012-11-08T21:04:56.420 回答
2

在片段中

//Allocate 1-D Array of Pointers, Array 'a'
a = (int** ) malloc( sizeof(int)*dimension);

注释与实际代码不符。在代码中,您为dimension整数分配空间,而不是指针。

由于指针可能大于 int,因此分配行的循环超出了分配的内存。

初始分配应为

a = malloc( sizeof(int*)*dimension);

或者

a = malloc( dimension * sizeof *a);

第二种形式的优点是它对于分配任何大小的数组总是正确的dimension

于 2012-11-08T21:05:17.740 回答
0

我发现了我的错误!这是一个无限 for 循环,位于我的其他“for”循环之一中!另外,正如上面许多人所说,我应该乘以 (int*) 而不仅仅是 (int)!太感谢了!

于 2012-11-08T21:30:35.953 回答
0

我花点时间编译了你的第一个示例,它运行良好,我认为错误可能是a必须是 type 的int **a。我还必须将类型添加到r变量i中。如果这不起作用,那么我认为您必须指定错误所在的行,并添加变量声明和#includes. 希望这可以帮助...

于 2012-11-08T20:22:59.410 回答