-1
I expected the following code to record the students' data, and then immediately erase it from memory:
testTurma. c
#include "aluno.h"
#include <stdlib.h>
int main(){
aluno *turma;
turma = malloc(3*sizeof(aluno));
turma[0] = regAluno("Joao",123,7.0,5.0);
turma[1] = regAluno("Maria",124,8.0,6.0);
turma[2] = regAluno("Jose",163,6.0,5.0);
for(int i = 0;i<3;i++) exibeAluno(turma[i]);
free(turma);
//Aqui eu esperava ou exibir lixo de memória, ou dar erro e abortar
for(int i = 0;i<3;i++) exibeAluno(turma[i]);
return 0;
}
But I get the following output:
Nome: Joao, Matr.: 123, Media: 6.00
Nome: Maria, Matr.: 124, Media: 7.00
Nome: Jose, Matr.: 163, Media: 5.50
Nome: (null), Matr.: 123, Media: 6.00
Nome: Maria, Matr.: 124, Media: 7.00
Nome: Jose, Matr.: 163, Media: 5.50
That is, it only erased the first property of the student struct that was reserved in the first memory space, someone could explain to me how the free() function actually works, and how I can free up all allocated memory space?
Rest of the code:
pupil. c
#include "aluno.h"
#include <stdlib.h>
#include <stdio.h>
aluno regAluno(char *nome,int matricula, float nota1,float nota2){
aluno a;
a.nome = nome;
a.matricula = matricula;
a.nota1 = nota1;
a.nota2 = nota2;
a.media = (nota1+nota2)/2;
return a;
}
aluno *criaPontAlunos(int size){
aluno *p;
p = malloc(size*sizeof(aluno));
return p;
}
void exibeAluno(aluno a){
printf("Nome: %s, Matr.: %d, Media: %.2f\n",
a.nome, a.matricula, a.media);
}
pupil. h
#ifndef ALUNO_H
#define ALUNO_H
typedef struct{
char *nome;
int matricula;
float nota1;
float nota2;
float media;
} aluno;
aluno regAluno(char *nome,int matricula, float nota1,float nota2);
aluno *criaPontAlunos(int size);
void exibeAluno(aluno a);
#endif
Could show the structure of the student struct?
– G. Bittencourt
According to the link insert link description here It was enough to perform the free (class).
– Gabriel Andrade
You need to see what you’re up to because this is really wrong, to give you a solution just knowing you need it, it’s not just a mistake in
free()
.– Maniero
@G.Bittencourt typedef struct{ char *name; int matricula; float Nota1; float nota2; float media; } student;
– Neo son