I am trying to normalize a C string that contains a number so that additional zeros are added in the beginning make the whole string contain MAXCOL characters (which is 8 ..)
Everything seems to be working fine up to the point where i add the original string back into the normalized string : Some random characters are being added idk how, it’s like i am adding characters that are after the \0 character, making the string look weird when shown on screen.
I hope someone has a clue as to what i am doing wrong.
To give you an idea, t_operande2D is a 2D array of char[MAXCOL]
void normaliser_operandes(t_operande2D mes_operandes){
// This procedure adds zeros to the beginning of each mes_operandes to have a normalized nbr of MAXCOL chars
//
// Lets say it receives mes_operandes[0] as 10, it will convert it to 00000010
int j, nombre_caracteres; // Nbr of original caracters
t_operande2D operandes_normalises; // The normalized output (temp variable)
for(int i=0; i<MAXLIGNE; i++){
// Count the original nbr of chars
nombre_caracteres = 0;
for(int j=0; (j<MAXCOL && mes_operandes[i][j]!='\0'); j++){
nombre_caracteres++;
}
// Add needed 0s to the beginning
for(j=0; j< MAXCOL - nombre_caracteres; j++){
operandes_normalises[i][j] = '0';
}
operandes_normalises[i][j] = '\0';
strncat(operandes_normalises[i], mes_operandes[i], nombre_caracteres);
strncpy(mes_operandes[i], operandes_normalises[i], MAXCOL);
}
}
EDIT: after the edit, the strncat is giving me the “stack around operandes_normalises was corrupted…” error 🙁
strcatexpects both of it’s arguments to be NUL terminated. By the looks of things,operandes_normalises[i]begins withMAXCOL - nombre_caracteresamount of'0'chars, but isn’t followed up by a NUL terminator ('\0') to indicate the end of the string.strcatwill look for the end of the string before appendingmes_operandes[i]tooperandes_normalises[i]. If the junk characters are between the'0'‘s andmes_operandes[i], then that’s your problem –operandes_normalises[i]is missing a terminator.If the junk characters are after
mes_operandes[i], thenmes_operandes[i]is the one that isn’t NUL terminated.Print out
operandes_normalises[i]after adding the'0'‘s to the start of the string to see if this is the case. By the looks of things I’m guessing there’s a good chance it is.ie. If
MAXCOL - nombre_caracteresis 5,operandes_normalises[i]could be:Therefore
mes_operandes[i]will be added after the junk characters.EDIT: Thought I might add,
strcatis unsafe, especially in the way it’s being used here – no checking to ensure thatmes_operandes[i]will fit inoperandes_normalises[i].Consider using
strncat, however note that it writes n + 1 characters to the destination. From the manpages: