我從線填充數據的結構,該行格式可以是3種不同的形式:
1 .-「LD‘(只是一個字)
2 .-’LD A「(只有2個字)
3.-」LD A,B「(第二個字由昏迷分隔)。
稱爲instruccion的結構只有3個指針指向每個部分(mnemo
,op1
和op2
),但是當爲第二個字分配內存時,有時malloc
會返回與第一個單詞相同的值。下面是與mallocs
代碼指出:2 mallocs返回相同的指針值
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("\nj%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("\n2j%xj2",nueva.op2);
}
return nueva;
}
當我打印指針恰好是相同的數字。 注意:函數char * nextET(char * line)返回行中第一個空格或製表符的方向,如果沒有則返回行尾的方向。
sepInst()
在程序中被多次調用,並且只有在多次調用它之後纔會啓動失敗。這些mallocs
跨我的所有程序都給我這麼頭痛。
對於SO問題,這是太多的代碼。請構建一個10行[最小測試用例](http://sscce.org),最好用英文... –
對不起,我不知道如何做一個小例子,因爲我不知道到底在哪裏在功能上的問題,但我翻譯的意見是英文 –
開始刪除所有不必要的東西(刪除它們後的所有行,你仍然觀察到你在你的問題中提到的相同的行爲)。 – betabandido