简体   繁体   English

尝试打印指针值时出现堆异常

[英]Heap exception when trying to print the value of a pointer

Sorry for my bad English. 对不起,我的英语不好。

I just started working on my school final's project and I encountered an error in my code... 我刚开始参加学校决赛的项目,却在代码中遇到错误...

The program is in C and it makes a matrix struck (with a starting pointer, num of rows and columns). 该程序用C语言编写,并产生矩阵(带有起始指针,行和列的数量)。 The first function should make a matrix with an enlargement of the num of rows and columns and zero out all the values(later it will be used for a diffrent perpece but nevermind that). 第一个函数应该创建一个矩阵,其中行和列的数量增加,并且所有值归零(此后将用于不同的性能,但不要介意)。 Later there is a function that prints the matrix out. 后来有一个函数可以打印出矩阵。

When the program get to the "printf" it breaks.. "Unhandled exception at 0x7789ea27 in image_pross.exe: 0xC0000374: A heap has been corrupted." 当程序进入“ printf”时,它会中断。 "Unhandled exception at 0x7789ea27 in image_pross.exe: 0xC0000374: A heap has been corrupted."

Here's the code: 这是代码:

#include <stdio.h>

#include <stdlib.h>

struct matrix

{
    int* ptr;

    int row;

    int column;

};

matrix ZFMatrix(matrix preMtx,int nColumn,int nRow);

void printMatrix (matrix mtx);


void main( int argc, char* argv[])
{
    int matrixAdd[3][3]={{1,1,1},{1,-8,1},{1,1,1}};

    matrix mtx;

    mtx.ptr=&matrixAdd[0][0];

    mtx.row=3;

    mtx.column=3;

        mtx= ZFMatrix(mtx,2,2);

    printMatrix(mtx);

}
matrix ZFMatrix(matrix preMtx,int nColumn,int nRow)

{
    matrix newMtx;


    newMtx.column=nColumn*2+preMtx.column;

    newMtx.row=nRow*2+preMtx.row;

    newMtx.ptr= (int*) malloc((newMtx.row)*(newMtx.column));

    int i,j,*tmp=newMtx.ptr;

    //zero out the matrix

    for (i=0; i<newMtx.column;i++)

    {

        for(j=0;j<newMtx.row;j++)

        {

            *newMtx.ptr=0;

            newMtx.ptr++;


        }

    }

    newMtx.ptr=tmp;

     return newMtx;

}

void printMatrix (matrix mtx)

{

    int i=0,j=0;

    for (;i<mtx.column;i++)


    {
        for(;j<mtx.row;j++)

        {


            printf("%d, ", *mtx.ptr);

            mtx.ptr++;
        }
        printf("\n");
    }
}
newMtx.ptr= (int*) malloc((newMtx.row)*(newMtx.column));

Should be: 应该:

newMtx.ptr= (int*) malloc((newMtx.row)*(newMtx.column) * sizeof(int));

You're allocating newMtx.row * newMtx.column bytes when you want integers 您需要整数时分配newMtx.row * newMtx.column 字节

Also, when you have a malloc() you should have a corresponding free() - Or you'll leak memory. 另外,当您有一个malloc()您应该有一个对应的free() -否则您将泄漏内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM