簡體   English   中英

為什么這個程序在釋放時會崩潰?

[英]Why does this program crash when freeing?

當我使用這一行並試圖釋放指針時,我試圖理解為什么這個程序會崩潰:

 t_mat *C=malloc(sizeof(t_mat));

但適用於以下行(沒有 memory 泄漏,沒有崩潰,值 53 是我通過反復試驗找到的最小值):

 t_mat *C=malloc(sizeof(t_mat)+53);

程序:(while(1) 循環用於 memory 泄漏測試,不影響崩潰)

#include <stdio.h>
#include <stdlib.h> 
typedef int t_mat[3][3];
t_mat* matice(t_mat A, t_mat B, char op)
{
    t_mat *C=malloc(sizeof(t_mat)+53);
    switch(op)
    {
    case '+':
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
                *C[i][j]=A[i][j]+B[i][j];
        return *C;
        break;
    case '-':
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
                *C[i][j]=A[i][j]-B[i][j];
        return *C;
        break;
    default:
        free(C);
        printf("Chyba\n");
        return NULL;
        break;
    }
}
int main()
{
    char op;
    scanf("%c",&op);
    getchar();
    t_mat A = {0,1,2,3,4,5,6,7,8},B= {0,1,2,3,4,5,6,7,8},*C;
    while(1)
    {
        C=matice(A, B, op);
        for(int i=0; i<3; i++)
            for(int j=0; j<3; j++)
                printf("%d\n",*C[i][j]);
        free(C);
        C=NULL;
    }
    return 0;
}

我在這里錯過了什么嗎?

一元*的優先級低於[] 你需要寫(*C)[i][j]

像這樣的陳述

*C[i][j]=A[i][j]+B[i][j];

printf("%d\n",*C[i][j]);

調用未定義的行為。 由於這個聲明,變量C的類型是int ( * )[3][3]

t_mat *C=malloc(sizeof(t_mat)+53);

所以首先你應該應用解引用運算符,然后才應用下標運算符

( *C )[i][j]=A[i][j]+B[i][j];

或者

printf("%d\n", ( *C )[i][j]);

否則程序有未定義的行為。

所以在 memory 分配中使用幻數53沒有任何意義。 寫吧

t_mat *C=malloc(sizeof(t_mat));

這是一個演示程序。

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

#define N   3
typedef int t_mat[N][N];

int main(void) 
{
    t_mat A = 
    { 
        { 0, 1, 2 }, 
        { 3, 4, 5 },
        { 6, 7, 8 }
    };
    
    t_mat B = 
    { 
        { 0, 1, 2 }, 
        { 3, 4, 5 },
        { 6, 7, 8 }
    };
    
    t_mat *C = malloc( sizeof( t_mat ) );
    
    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            ( *C )[i][j] = A[i][j] + B[i][j];
        }
    }
    
    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            printf( "%2d ", ( *C )[i][j] );
        }
        
        putchar( '\n' );
    }
    
    putchar( '\n' );
    
    free( C );
    
    return 0;
}

程序 output 是

 0  2  4 
 6  8 10 
12 14 16

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM