c - 大维度值错误 - 运行时检查失败 #2 - 变量 'mat' 周围的堆栈已损坏

标签 c pointers memory memory-management access-violation

我收到以下错误:

运行时检查失败#2 - 变量“mat”周围的堆栈已损坏”在控制台中给出结果后。

但是,据我观察,CreateMatrix 函数对于较大的矩阵维度会引发访问冲突。例如适用于 5x7,不适用于 50 x 70。 怎么办?

程序只是创建矩阵(初始化)并设置+打印矩阵元素。

此外,问题中的警告是我被要求不要在 main() 中使用类似“Matrix* mat..”的内容。否则,解决方案很简单。

我希望你能理解我的问题。

更详细的代码:

struct Matrix
{
    int width;
int height;
int* data;
};
typedef struct Matrix Matrix;

int main()
{
    Matrix mat, *matP;

    //1. Things that Works...
    matP = CreateMatrix(&mat,700,500);         
    SetValue(matP,500,600,-295);
    int val=GetValue(matP,500,600);
    printf("%d\n",val); 


    //2. Things that does NOT work... !!!
    CreateMatrix(&mat,700,500); // this is C-style "Call-By-Reference" CreateMatrix2()
    SetValue(&mat,500,600,-295); // ERROR in this function, while setting matrix element
    val=GetValue(&mat,500,600);

    printf("%d\n",val); 
}


void SetValue(Matrix* mat,int row,int col,int value)
{
    *(mat[(mat->width*(row-1)) + (col-1)].data) = value;// <------ ERROR here

    // Unhandled exception at... Access violation writing location 0x000001f4
}

Matrix * CreateMatrix(Matrix *mat,int width,int height)
{        
    // mat = (Matrix*)malloc(width*height*(sizeof(Matrix))); // As told by Salgar
    mat->height = height;
    mat->width = width;

    for(int i=0; i < height; i++ )
    {
        for(int j=0; j < width; j++ )
        {
            mat[width*i + j].width = width;
            mat[width*i + j].height = height;
            mat[width*i + j].data = (int*)malloc(sizeof(int));
        }
    }
}

最佳答案

当您分配给这一行的 mat 时:

 mat = (Matrix*)malloc(width*height*(sizeof(Matrix)));

它正在更改mat的本地范围副本,因此您在调用函数中在堆栈上声明的mat没有发生任何事情。

您需要将指针传递给指针,而不是在堆栈上声明一个指针,因为您无法使用在堆上声明的内容覆盖该指针。

Matrix* mat;
CreateMatrix(&mat,700,500);

Matrix * CreateMatrix(Matrix **mat,int width,int height)
{
   ...
   *mat = malloc(etc)
   ...
}

关于c - 大维度值错误 - 运行时检查失败 #2 - 变量 'mat' 周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17045013/

相关文章:

c - GCC libm 不工作

c++ - 如何使用引用调用从 C++ 函数中获取 char** 类型变量的值?

ios - 什么是高 iOS 内存使用率?

c - C 中的字符串搜索

c - 进程结束/死亡时共享 POSIX 对象清理

c++ - 尝试创建一个 3D vector ,该 vector 将保存指向指向 unsigned char 的指针的指针

c++ - 关于指针作为数组的一些疑问?

memory - 如何判断内存页是否被标记为只读?

node.js - Nodejs将参数传递给fork对象

将二进制浮点 "1101.11"转换为十进制 (13.75) 的正确算法?