Note that there are some explanatory texts on larger screens.

plurals
  1. POtwo mallocs returning same pointer value
    primarykey
    data
    text
    <p>I'm filling a structure with data from a line, the line format could be 3 different forms:<br> 1.-"LD "(Just one word)<br> 2.-"LD A "(Just 2 words)<br> 3.- "LD A,B "(The second word separated by a coma).<br> The structure called instruccion has only the 3 pointers to point each part (<code>mnemo</code>, <code>op1</code> and <code>op2</code>), but when allocating memory for the second word sometimes <code>malloc</code> returns the same value that was given for the first word. Here is the code with the <code>mallocs</code> pointed:</p> <pre><code>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);&lt;----------------------------------- 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);&lt;---------------------------------- 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; } </code></pre> <p>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.</p> <p><code>sepInst()</code> is called several times in a program and only after it has been called several times it starts failing. These <code>mallocs</code> across all my program are giving me such a headache.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload