C program randomly inserting random name of function into my array

I have the following program that converts decimal to binary:

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

int main() {
    printf("Number (decimal): ");
    int no;
    scanf("%d", &no);

    char bin[64];
    while (no > 0) {
        for (int i = strlen(bin); i > 0; i--) {
            bin[i] = bin[i - 1];

        int bit = no % 2;
        char digit = bit + '0';
        bin[0] = digit;

        no /= 2;

    printf("%s", bin);

    return 0;

The program works correctly, but randomly the string "ttime__vdso_get" gets appended on the end.

The numbers that make it happen are different every time I compile.

1: 1

2: 01ttime_vsdo_get

3: 10ttime_vsdo_get

It becomes a little different when the numbers get bigger:

100039: [email protected]

10000000000000000000000000000: ttime

What is happening?

If I had to diagnose it I'd say that I've managed to make a compiling program that's pulling memory from the wrong places. I don't know how how I managed to do it, though.

I'm using GCC, if it matters.



answered 5 months ago wookiekim #1

It may be because of this line of code :

for (int i = strlen(bin); i > 0; i--) {
        bin[i] = bin[i - 1];

Try replacing strlen(bin) with 63.

It may also be a good idea to initialize your array bin with 0s.

answered 5 months ago fenghengzhi #2

try filling varible char bin[64] with 0

answered 5 months ago Stargateur #3

Just do char bin[64] = "";, never forget that a valid string is nul [email protected]��[email protected]

And strlen() return an size_t !

I can also advice you to use char bin[sizeof no * CHAR_BIT + 1] = ""; that will use a correct maximum size for your string.

comments powered by Disqus