我正在用一行中的数据填充结构,行格式可以是 3 种不同的形式:
1.-“LD”(只有一个词)
2.-“LD A”(仅2个字)
3.- "LD A,B "(第二个单词以逗号分隔)。
名为 instruccion 的结构只有 3 个指针指向每个部分(mnemo
、op1
和 op2
),但是在为第二个单词分配内存时有时,malloc
返回的值与为第一个单词指定的值相同。这是带有 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()
在程序中被多次调用,只有在多次调用后才开始失败。我所有程序中的这些 malloc
让我非常头疼。
最佳答案
主要有两种可能性。
要么您在程序中的其他位置释放内存(搜索对 free
或 realloc
的调用)。在这种情况下,您看到的效果是完全良性的。
或者,您可能遇到内存损坏,很可能是缓冲区溢出。短期解决方法是使用专门的工具(memory debugger)。选择您的平台上可用的一个。该工具将需要重新编译(重新链接)并最终告诉您代码到底在哪里超出了先前定义的缓冲区限制。可能存在多个违规代码位置。将每一项都视为严重缺陷。
一旦您厌倦了这种研究,请学习使用 const 限定符并将其与所有变量/参数声明一起使用,这样您就可以干净地完成它。这不能完全防止缓冲区溢出,但它会将它们限制为旨在成为可写缓冲区的变量(例如,您的问题中涉及的那些显然不是)。
关于c - 两个 malloc 返回相同的指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776607/