Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange problem with variable in C program

This code is to change decimal "n" to binary that I wrote like this:

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

int main(){
    char str[] = "";
    int a = 5;
    int n = 5;
    while(n > 0){
        if (n % 2 == 0) {
            strcat(str,"0");
        } else {
            strcat(str, "1");
        }
        n = n / 2;
    }
    strrev(str);

    printf("%s", str);
    return 0;
}

The problem here is, when I tried to debug and see the variable changing, the "a" changed in a very strange way, although I don’t do anything to "a". Why is it like that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The array str, because it doesn’t have an explicit size, is sized to exactly store what it is initialized with. And because an empty string only contains 1 character, namely a terminating null byte, your array is 1 element in size.

This means str isn’t large enough to hold any string that’s not an empty string, so using strcat on it causes the function to write past the end of the array, triggering undefined behavior. In this case, it manifests as writing into another variable which happens to be adjacent to the array in memory.

The array must be sized properly to hold whatever string it might hold, i.e.:

char str[33] = "";

This gives you enough space to store the binary representation of any nonnegative 32 bit integer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading