Accessing the allocation causes program to stop working

Asked

Viewed 68 times

0

I’m having a problem accessing a subscriber struct

typedef struct Inscrito {
     char nome[50];
     float cadastro;
     float nota;
};

Inscrito *inscritos = NULL;

it is as a global variable and every time I access it somehow (either to check an error or to put the values inside it after the error has been allocated)

(data is the file variable . txt I opened)

int Conta_MaioresNotas(FILE *Dados){

float NotaMin;
char info[20];
float numero;
int contador = 0, i = 0;

printf("Voce escolheu as maiores notas\n");
printf("Apartir de qual nota voce quer? ");
scanf("%f", &NotaMin);

while(!feof(Dados)){
    fscanf(Dados,"%s", &info);
    numero = atof(info);
    if(numero && numero > NotaMin && numero < 1001){
        contador++;
        printf("%.2f\n", numero);
    }
}
printf("%d\n", contador);
VoltaInicio(Dados);


inscritos = (Inscrito *) malloc(contador*sizeof(Inscrito));

if(inscritos == NULL) {printf("Deu erro meu amigo\n"); exit(-1);}


 while(!feof(Dados)){
    fscanf(Dados,"%s ", &info);
    numero = atof(info);
    if(!numero){
        strcat(inscritos[i].nome, " ");
        strcat(inscritos[i].nome, info);
        }
    else{
        if(numero > 1000){
            inscritos[i].cadastro = numero;

            }
        else{
            if(numero > NotaMin){
                inscritos[i].nota = numero;
                i++;
                }
            else{
                strcpy(inscritos[i].nome,"");
                inscritos[i].cadastro = 0.0;
                }
            }
        }    
}
VoltaInicio(Dados);

The while that gives the error, but I don’t understand why, the program sticks and closes "The program stopped working. A problem caused the program to stop working"

/*printf("Cadatrados filtrados:\n");
for(i = 0; i < contador; i++)
{
    printf("Nome: %s\nCadastro: %f\nNota: %.2f\n\n", inscritos[i].nome, inscritos[i].cadastro, inscritos[i].nota);
}*/


return contador;
}

I commented this one to show that it is not him who is giving error, only to be able to show the code until the end

inserir a descrição da imagem aqui (I tried to pass the pointer entered to the function and gave the same error)

1 answer

0

The way the code was presented is a little difficult to determine with certainty what the problem is, even because it was not informed completely, but there are some considerations.

First of all, I don’t encourage the use of global variables. I understand how easy that is, but you can be responsible for these mistakes if you don’t pay attention to what you do. It’s important to note that global variables can be changed anywhere, so it’s very easy for you to end up releasing or overwriting data from global variables through an unforeseen execution flow. Develop your software by keeping in mind the paths in which the code can be executed. Make your functions perform only one task, not functions that do all that is to be done.

As for the code presented, I first believe that it did not copy directly from what it did because there is an error right in the declaration of struct, when using this struct with typedef (which is commendable, appreciate the practice as you did), it is necessary to define the new name after the end of the declaration of struct, before the semicolon, in your example:

typedef struct Instrucao{
  ...
} Instrucao; //<---Erro

Only for this reason would the example provided no longer perform, but I do not believe that is the case.

I also do not believe that this is the case of memory release, but keep in mind that you must free the memory allocated in the variable instructions using the function free(), due to the dynamic allocation carried out.

As to your specific error, you should also note that within the While you suspect you have an error, you use the function strcat, and she, as the name says, performs a concatenation string. Initially the name in question is empty, has absolutely nothing, so there is a small problem in wanting to concatenate a string to nothing, the value is literally emptiness, but most compilers won’t complain about it superficially, if you use an execution parser like Valgrind, you will find that it will complain about some errors related to instructions that depend on memory that has not yet been initialized (its string before concatenating anything).

This concatenation is also dangerous because the variable name in his struct Instrucao has been declared to have a maximum length of 50 characters, so it is possible that some of the concatenations you are performing exceed 50 characters, which means that one of the names has more than 50 characters, or an improper concatenation is happening and exceeding the character limit you have allocated, causing what is called Smashing stack, basically you’re using more characters than you reported.

If the problem is not in the name in the instructions, it may be in the character array info, which has support for only 20 characters, so one of the names or surnames may exceed 20 characters and cause the error reported.

It turns out that not always exceed the size you allocated will cause an error like this, what happens is a Undefined behaviour or undefined behavior, sometimes it can work, sometimes it won’t, it will be variable as your program runs and therefore it won’t be trusted to use it. It is important that you change these strings to a dynamic allocation or increase their size to see if this solves the problem in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.