0

I made this method for a test and for some reason the malloc is not working. When I comment it it does work, but otherwise it will just say the program has stopped working.

typedef struct { int NroUSP; // chave primária int curso; int estado; int idade; bool valido; // para exclusão lógica } REGISTRO; typedef struct s { int NroUSP; // chave primária int curso; int estado; int idade; bool valido; struct s* prox; } NO; typedef struct { NO* inicio; } LISTA; 

These are the structures I used ^

EDIT: THE PROBLEM WAS THIS ASTERISK RIGHT BEFORE AUX

void ex6(){ REGISTRO* aux; FILE *arq = fopen("C:\\Users\\jujuc_000\\Desktop\\Teste\\dados.bin","rb"); FILE *arq2 = fopen("C:\\Users\\jujuc_000\\Desktop\\Teste\\ex6.bin","wb"); LISTA l; l.inicio = NULL; NO*p = (NO*)malloc(sizeof(NO)); // this is the test malloc if(arq){ while(1==fread(&aux,sizeof(REGISTRO),1,arq)){ /*p = (NO*)malloc(sizeof(NO)); // this is the one I want to keep p->NroUSP = aux->NroUSP; p->curso = aux->curso; p->estado = aux->estado; p->idade = aux->idade; p->valido = aux->valido; if(!l.inicio){ l.inicio = p; } p=p->prox;*/ } } fclose(arq); fclose(arq2); } 
4
  • 1
    Where is the definition of "NO"? Also, don't cast malloc: stackoverflow.com/questions/1565496/… . It's dangerous. Commented May 13, 2015 at 0:14
  • Is it failing at malloc or at p=p->prox? Commented May 13, 2015 at 1:03
  • How is it not working? If there's an error message, please include it in the question. Commented May 13, 2015 at 1:28
  • "THE PROBLEM WAS THIS ASTERISK RIGHT BEFORE AUX" - so precisely what Ken's answer described (sigh). Commented May 13, 2015 at 2:19

2 Answers 2

1

fread(&aux,sizeof(REGISTRO),1,arq) is most likely your problem; aux is a pointer to a REGISTRO, but you try to read in a full REGISTRO into it, which more than likely overwrites memory, causing the apparent malloc failure in the next line. Change the declaration to:

REGISTRO aux; 

And things should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Nope :/ still not working. Plus I tried putting the malloc both inside and outside the loop, and neither works.
0

Try the following:

  1. Use feof() instead of if(arq) ...
  2. Set p->prox = NULL;
  3. Either declare 'REGISTRO aux' or allocate memory to 'aux' if declaring it as a pointer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.