Icy TV Icy TV - 1 year ago 54
C Question

WHy does this code crash, when used with bin?

As the title suggests, I don't know where my mistake is with binary.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char binary[360];

void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];

while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.

itoa(*s, output, 2);

strcat(binary, output);

++s;
}

}

int main(int argc, char *argv[])
{

int i, n;

//printf("argc: %i\n", argc);
if (argc != 3)
{
puts("Converter [Text] [hex|dec|bin]");
return 0;
}
FILE *f = fopen("Output.txt", "a");
for (i = 0; i < strlen(argv[0]); i++)
{
if (strcmp(argv[2], "hex") == 0)
fprintf(f, "%X ", (unsigned int) argv[1][i]);
else if (strcmp(argv[2], "dec") == 0)
fprintf(f, "%i ", (unsigned int) argv[1][i]);
else if (strcmp(argv[2], "bin") == 0)
for (n = 0; n < strlen(argv[1]); n++)
{
printstringasbinary(argv[1][i]);
}
fprintf(f, "%s ", binary);

}
fclose(f);

return 0;
}

Answer Source

You iterate through the characters of argv[1][i], whereas i can take on values up to the string length of argv[0]. Depending on whether argv[0] is "longer" than argv[1], this can lead to a seg fault. Did you mean printstringasbinary(argv[1][n]) instead of printstringasbinary(argv[1][i])? BTW: why - as pointed out by LPs - do you iterate through argv[1] at all?

for (i = 0; i < strlen(argv[0]); i++)
....

        for (n = 0; n < strlen(argv[1]); n++)
        {
            printstringasbinary(argv[1][n]);
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download