如何在C中正确分配和传递指针

时间:2012-11-07 15:42:55

标签: c memory-management

我有三个文件:

something.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);

something.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");
 }

的main.c

#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)

1 个答案:

答案 0 :(得分:0)

此代码没有任何问题,除了由于您分配矩阵然后将其分配给使用该函数创建的矩阵而导致的内存泄漏,而不释放先前分配的矩阵。