簡體   English   中英

Malloc 沒有分配足夠的內存

[英]Malloc does not allocate suficient memory

運行代碼時,我檢查指針是否已分配足夠的內存,或者它是否保持為 NULL,但可以為它分配我們想要的全部內存量。 我們將 C11 與 Clion 一起使用。

代碼的第一部分:

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

#define MAX_CHAR 100

typedef struct {
    char name[MAX_CHAR];
    char escuderia[MAX_CHAR];
    int dorsal;
    int reflejos;
    int c_fisica;
    int temperamento;
    int gest_neumaticos;
}DatosPiloto;

typedef struct {
    char type[26];
    int vel;
    int acc;
    int cons;
    int fiab;
}Pieza;

typedef struct {
    char name_cat[26];
    Pieza *pieza;
    int num_piezas;
}Categorias;

Int main 和函數調用:

int main (int argc, char **argv) {

    char sel[MAX_CHAR];
    int opt = 0;
    int error = 0, datosok = 0;
    // Opcion 1
    DatosPiloto datosPiloto;
    Categorias *categorias;

    if (argc == 5) {
        error = abreFichero(argv);
    }
    else {
        printf("Error. El programa tiene que recibir 4 argumentos.");
        error = 1;
    }


    if (error == 0) {
        leerArchivos(argv, &categorias);
    ...
    ...

argc 是一個始終為 5 的整數,**argv 是 clion 中導入文件的指針,其中 [0] 是第一個文件,[4] 是最后一個文件。

功能是:

void leerArchivos (char **argv, Categorias **categorias) {
    FILE *Piezas;
    FILE *GPs;
    FILE *Corredores;
    FILE *Base;

    int num_categorias = 0, lineas_leer = 0;
    int j = 0, i = 0, cat_count = 0;
    char basura;
    Piezas = fopen(argv[1], "r");
    GPs = fopen(argv[2], "r");
    Corredores = fopen(argv[3], "rb");
    Base = fopen(argv[4], "rb");


    fscanf(Piezas, "%d", &num_categorias);

    printf("%d\n", num_categorias);

    *categorias = (Categorias *) malloc(num_categorias * sizeof(Categorias));

    if (*categorias == NULL || sizeof(categorias) < num_categorias * sizeof(Categorias)) {
        printf("ERROR! Memory not allocated or smaller that desired.\n");
    }else {
    ...
    ...

sizeof不會告訴您分配了多少內存。 沒有標准的方法可以找出答案。 使用malloc() ,您要么至少獲得您要求的字節數,要么獲得NULL sizeof(categorias)是指針的大小,無論是否分配了多少內存。 @M 厄姆

下面就OK了。

*categorias = (Categorias *) malloc(num_categorias * sizeof(Categorias));
if (*categorias == NULL) {
    printf("ERROR! Memory not allocated or smaller that desired.\n");
} else {

不需要演員。

分配到引用數據的大小比類型的大小更清晰。

*categorias = malloc(sizeof *categorias * num_categorias);

num_categorias值小於 0 會產生問題。 考慮一個無符號類型。

// int num_categorias = 0
unsigned  num_categorias = 0
// or 
size_t num_categorias = 0

num_categorias的值會產生問題。 一些較舊的系統即使成功也會返回NULL

if (*categorias == NULL && num_categorias != 0) {

暫無
暫無

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

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