【问题标题】:Error trying to allocate a bidimensional array in C [closed]尝试在 C 中分配二维数组时出错 [关闭]
【发布时间】:2023-04-01 14:13:01
【问题描述】:

问题信息: 编译器:mingw32-gcc.exe (tdm-1) 4.7.1 CLI: gcc z:\ES16\main.c -o main.exe 代码测试:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIM 3

void print_matrix(int**  _mtx);
int main()
{
    int i,j;
    srand(time(NULL));
    int **mtx;
    mtx = (int **)malloc(sizeof(int*)*DIM);
    for (i=0;i<DIM;i++)
    {
        mtx[i] = (int *)malloc(sizeof(int*)*DIM);
    }

    for(i=0;i<DIM*DIM;i++)
    {
        for(j=0;j<DIM;j++)
        {
           *((*(mtx)) + (i * DIM + j))= (int)(rand() % 10 + 1);
        }


    }
    print_matrix(mtx);

    free(mtx);

    return 0;
}

void print_matrix(int** _mtx)
{
    int i,j;
    for(i=0;i<DIM;i++)
    {
        for(j=0;j<DIM;j++)
        {
            printf("%d  ",*((*(_mtx)) + (i * DIM + j)));
        }
        printf("\n");
    }
}

下面我们有几点让我们认为问题出在 Windows 而不是编译器:

  1. 程序在 Linux 下运行没有问题
  2. 适用于 Windows 10 Code::Blocks 16.01 及其默认编译器
  3. 适用于 Code::Blocks 12.11 和 mingw32-gcc.exe (tdm-1) 4.7.1

尽管上面的所有事情程序都无法从启动 windows默认shell。

有时程序在不打印矩阵的情况下崩溃,有时它在打印部分矩阵后崩溃。
总是没有任何特别的原因。

考虑到所有这些问题,问题似乎出在 Windows 上,因此我们希望对问题进行一些澄清。

【问题讨论】:

  • 所以你甚至不考虑你的代码有错误的可能性吗?好的。我至少看到其中两个...
  • valgrind 说:==25847== Invalid read of size 4 ==25847== at 0x100000DB1: print_matrix (mem31.c:41) ==25847== by 0x100000E72: main (mem31.c:27) ==25847== Address 0x100a7f5a8 is 0 bytes after a block of size 24 alloc'd ==25847== at 0x100007E81: malloc (vg_replace_malloc.c:302) ==25847== by 0x100000E17: main (mem31.c:15)
  • 我发现至少有两个巨大的错误。
  • @EugeneSh。使用valgrind 是在其他人的代码中发现问题的一种方法,无需费力思考。哪一个,因为我应该关注会议,这对我来说是件好事。但这是一个很好的证明,测试不能显示没有错误。
  • 此外,您的代码中的任何地方都没有“双向”(即二维)数组,也没有任何类似的东西。

标签: c windows gcc memory memory-management


【解决方案1】:

发现 4 个问题:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIM 3

void print_matrix(int**  _mtx);
int main()
{
    int i,j;
    srand(time(NULL));
    int **mtx;
    mtx = malloc(sizeof(int*)*DIM);
    for (i=0;i<DIM;i++)
    {
        mtx[i] = malloc(sizeof(int)*DIM);  /* 1: sizeof int, not int* */
    }

    for(i=0;i<DIM;i++)  /* 2: just DIM, not DIM*DIM */
    {
        for(j=0;j<DIM;j++)
        {
           mtx[i][j]= (int)(rand() % 10 + 1); /* 3: i * DIM + j   magic is used if you have a 1 dimension array, but want to access it as two dimensions */
        }
    }
    print_matrix(mtx);

    free(mtx);

    return 0;
}

void print_matrix(int** _mtx)
{
    int i,j;
    for(i=0;i<DIM;i++)
    {
        for(j=0;j<DIM;j++)
        {
            printf("%d  ",_mtx[i][j]); /* 4: same as 3 */
        }
        printf("\n");
    }
}

【讨论】:

  • 谢谢。你知道为什么它在 linux 下没有任何问题吗?
  • 纯属运气。 malloc() 调用可能会返回比您请求更多的内存,以及多少(如果有)取决于 libc 实现
猜你喜欢
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多