I m filling a structure with data from a line, the line format could be 3 different forms:
1.-"LD "(Just one word)
2.-"LD A "(Just 2 words)
3.- "LD A,B "(The second word separated by a coma).
The structure called instruccion has only the 3 pointers to point each part (mnemo
, op1
and op2
), but when allocating memory for the second word sometimes malloc
returns the same value that was given for the first word. Here is the code with the mallocs
pointed:
instruccion sepInst(char *linea){
instruccion nueva;
char *et;
while(linea[strlen(linea)-1]==32||linea[strlen(linea)-1]==9)//Eliminating spaces and tabs at the end of the line
linea[strlen(linea)-1]=0;
et=nextET(linea);//Save the direction of the next space or tab
if(*et==0){//If there is not, i save all in mnemo
nueva.mnemo=malloc(strlen(linea)+1);
strcpy(nueva.mnemo,linea);
nueva.op1=malloc(2);
nueva.op1[0]= k ;nueva.op1[1]=0;//And set a "K" for op1
nueva.op2=NULL;
return nueva;
}
nueva.mnemo=malloc(et-linea+1);<-----------------------------------
strncpy(nueva.mnemo,linea,et-linea);
nueva.mnemo[et-linea]=0;printf("
j%xj",nueva.mnemo);
linea=et;
while(*linea==9||*linea==32)//Move pointer to the second word
linea++;
if(strchr(linea, , )==NULL){//Check if there is a coma
nueva.op1=malloc(strlen(linea)+1);//Do this if there wasn t any coma
strcpy(nueva.op1,linea);
nueva.op2=NULL;
}
else{//Do this if there was a coma
nueva.op1=malloc(strchr(linea, , )-linea+1);<----------------------------------
strncpy(nueva.op1,linea,strchr(linea, , )-linea);
nueva.op1[strchr(linea, , )-linea]=0;
linea=strchr(linea, , )+1;
nueva.op2=malloc(strlen(linea)+1);
strcpy(nueva.op2,linea);printf("
2j%xj2",nueva.op2);
}
return nueva;
}
When I print the pointers it happens to be the same number. note: the function char *nextET(char *line) returns the direction of the first space or tab in the line, if there is not it returns the direction of the end of the line.
sepInst ()
在一个程序里被多次调用, 只有在它被调用过几次后才开始失效。 在我的所有程序里这些 mallocs
都让我头疼。