I was trying to convert a decimal from [0, 255]
to a 8
bit binary number, where each bit will be separated by a comma and a space. I tried the following (eventually it worked, except for the last bit does not require any separator ):
#include <stdio.h>
#include <stdlib.h>
char* atobin(int input) {
char *str = malloc(0);
int index, count = 0;
if (input > 255| input < 0) {
printf ("Input out of range. Abort.\n");
exit(EXIT_FAILURE);
}
for (index = 7; index >= 0; index--) {
*(str + (count++)) = (input >> index & 1) ? '1' : '0';
*(str + (count++)) = ',';
*(str + (count++)) = ' ';
}
*(str + count) = '\0';
return str;
}
int main(int argc, char *argv[]) {
printf("%s\n", atobin(atoi(argv[1])));
return EXIT_SUCCESS;
}
Now I have a few questions:
- I used
malloc(0)
; as far as I am concerned, it will allocate no memory from the heap. So, how/ why is it working? - Is the declaration
*(str + count) = '\0';
necessary? - Is there any way to optimize this code?
UPDATE
To carry on this experiment, I have taken the atobin
function in to a .h
file. This time it creates some problems.
Now I add my last question:
What should be minimum integer to be used for the parameter of malloc
? Some trial-and-error method makes me guess it should me 512
. Any idea?