0

我有三个文件:

某事.h

typedef struct {
    int size_t;
    char *c;
} p;

p ** createMatrix(int r, int c);

void printMatrix(p **matrix, const int r, const int c);

某事.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "something.h"

p **
createMatrix(int r, int c)
{
    int rowsize=r*2+1;
    int colsize=c*2+1;

    /* memory alloc of rows */
    p **matrix=malloc(rowsize*sizeof(p *));
    int k;
    for(k=0; k<rowsize; k++)
    {
        /* memory alloc of columns */
        matrix[k]=malloc(colsize*sizeof(p));
    } 
    int i, j;
    for(i=0; i<rowsize; i++)
    {
        for(j=0; j<colsize; j++)
        {
            /* columns is between letters */
            if(j%2!=0)
        {   
                matrix[i][j].size_t=7;
                matrix[i][j].c=malloc(8*sizeof(char));
                strcpy(matrix[i][j].c,"       ");
        }
        else if(i%2==0 && j%2==0)
            {
                matrix[i][j].size_t=1;
                matrix[i][j].c=malloc(sizeof(char));
                *(matrix[i][j].c)='a';
            }
            else
            {
                matrix[i][j].size_t=1;
                matrix[i][j].c=malloc(sizeof(char));
                *(matrix[i][j].c)=' ';
            }
        }
    }       
    return matrix;
}

void
printMatrix(p **matrix, const int r, const int c)
{
    int rowsize=r*2+1;
    int colsize=c*2+1;
    printf("\n");
    int i, j;
    for(i=0; i<rowsize; i++)
    {
        printf("\t");
        for(j=0; j<colsize; j++)
        {
            if(matrix[i][j].size_t==1)
                printf("%c", *matrix[i][j].c);
            else
                printf("%s", matrix[i][j].c);

        }
        printf("\n");
    }
    printf("\n");
 }

主程序

#include <stdlib.h>
#include <stdio.h>
#include "something.h"    

void
printMenufunction(p **matrix, int rows, int cols)
{
    int rowsize=rows*2+1;
    int colsize=cols*2+1;
    /* memory alloc of rows */
    matrix=malloc(rowsize*sizeof(p *));
    int i;
    for(i=0; i<rowsize; i++)
    /* memory alloc of columns */
        matrix[i]=malloc(colsize*sizeof(p));
    matrix=createMatrix(rows, cols);
}

int
main(void)
{
    int rows, cols;
    p **matrix;
    char *stringtemp;
    printf("ask for row and col in form (5x5):\n");
    scanf("%s", stringtemp);
    sscanf(stringtemp, "%dx%d", &rows, &cols);
    printMenufunction(matrix, rows, cols);
    printMatrix(matrix, rows, cols);
    return 0;
}

这个简化的版本给我带来了分段错误。我不明白我要在哪里访问未分配的内存?有人可以解释一下吗?(SSCCE)

4

1 回答 1

0

这段代码没有任何问题,除了内存泄漏,因为您分配了矩阵,然后将其分配给使用该函数创建的矩阵,而没有释放先前分配的矩阵。

于 2012-11-07T16:58:17.197 回答