I just write a code for my own itoa (just for positive numbers) and I try to make it as efficient possible, I display the value from inside the function and from main, and it works, but when I remove the printf line from inside the function the code doesn't work anymore, does anybody knows why?
This is where it works
This is where it doesn't work
Thank you for your time! have a nice day
The code:
#include<stdio.h>
#define uint8_t unsigned char
#define uint16_t unsigned int
/*Prototipos de funciones*/
uint8_t *UART0_itoa(uint16_t number, uint8_t base);
/*Función principal*/
void main(){
uint8_t *cadena;
cadena = UART0_itoa(255, 16);
printf("The String in main: %s\n",cadena);
}
/*Declaración de funciones*/
uint8_t *UART0_itoa(uint16_t number, uint8_t base){
uint8_t *aux;
*aux = '\0';
while(number){
*--aux = (number%base>9)?(number%base)+'7':(number%base)+'0';
number/=base;
}
//printf("The String in the function: %s\n",aux);
return aux;
}
The problem is that you are not allocating any memory to aux
- it is an uninitialized pointer. Anything that you write to it, including the initial assignment of *aux = '\0'
, is undefined behavior.
You need to change the code to take the output buffer, or allocate it dynamically with malloc
. An attempt to write the number backwards is a nice one - you can make it work by passing the end of buffer, as follows:
uint8_t *UART0_itoa(uint16_t number, uint8_t base, char *aux){
while(number){
*--aux = (number%base>9)?(number%base)+'7':(number%base)+'0';
number/=base;
}
return aux;
}
and calling
char buf[16];
cadena = UART0_itoa(255, 16, &buf[15]);