【问题标题】:Malloc does not allocate suficient memoryMalloc 没有分配足够的内存
【发布时间】:2020-03-18 19:26:13
【问题描述】:

在运行代码时,我检查指针是否已分配足够的内存,或者它是否保持为 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 不会告诉您如何分配 mch 内存。没有标准的方法可以找出答案。使用malloc,您要么至少获得所需的字节数,要么获得NULL。而sizeof(categorias) 是指针的大小,不管是否分配给它以及分配多少内存。

标签: c malloc clion


【解决方案1】:

sizeof 不会告诉您分配了多少内存。没有标准的方法可以找出答案。使用malloc(),您要么至少获得所需的字节数,要么获得NULLsizeof(categorias) 是指针的大小,无论是否分配了以及分配了多少内存。 @M Oehm

下面的没问题。

*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 会产生问题。考虑一个 unsigned 类型。

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

num_categorias 的值会产生问题。一些旧系统即使成功也会返回NULL

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

【讨论】:

  • 轻松尝试回复有关该问题的内容,我们知道其余的代码,我们希望这样,因为它需要像这样。没有无符号,更好的整数,malloc 中的强制转换......谢谢!
猜你喜欢
  • 2019-11-18
  • 2014-04-24
  • 1970-01-01
  • 2011-02-09
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多