When running the code I check if the pointer has been allocated suficient memory or if it stays at NULL but it can be assigned the whole quantity of memory we desired. We are using C11 with Clion.
First part of the code:
#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 and funcion calling:
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 is an integer with a value of 5 always and **argv is the pointer with the files imported in clion, where [0] is the first file and [4] is the last one.
And the function is:
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
does not tell you how mch memory has been allocated. There's no standard way to find that out. Withmalloc
, you either get at least the amount of bytes you asked for or you getNULL
. Andsizeof(categorias)
is the size of a pointer, no matter whether and how much memory is allocated to it. – M Oehm