VERY strange problem. My program hangs unless I add a test variable and never use it.

This is a discussion on VERY strange problem. My program hangs unless I add a test variable and never use it. within the C Programming forums, part of the General Programming Boards category; the input of the function is a binary number, for example "10110" is the one being passed as i test ...

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    11

    VERY strange problem. My program hangs unless I add a test variable and never use it.

    the input of the function is a binary number, for example "10110" is the one being passed as i test this. The function is supposed to convert it to a hexadecimal. anyway, it's not finished, but this one thing is infuriatingly holding me up.

    for some reason a simple malloc statement is making my program hang. but when i tried to make another variable and malloc it, everything worked fine. It also is noteworthy that WHERE i put this test = malloc(5) matters, in some places it works, and in others the program hangs.

    I have no idea what's going on :[

    Code:
    char * bin2Hex(char *binary){
        char *paddedBin, *hexValue, *temp, *test;
        int pad, strLength, i, j, hexLength;
    
        strLength = strlen(binary);
    
        while (strLength % 4 != 0)
            strLength++;
    
        pad = strLength - strlen(binary);
        paddedBin = malloc(strLength);
    
        for(i = 0; i < strLength; i++)
            paddedBin[i] = '\0';
    
        for(i = 0; i < pad; i++)
            paddedBin[i] = '0';
    
        printf("test 1");
        test = malloc(5);      ///IF I REMOVE THIS LINE THE PROGRAM HANGS 
        printf("test 2");
        strcat(paddedBin, binary);
        printf("test 3");
    
        hexLength = strLength/4;
        hexValue = malloc(hexLength);   //PROGRAM HANGS HERE IF I REMOVE test = malloc(5);
    
        for(i = 0; i < hexLength; i++){
            temp = malloc(4);
            for(j = 0; j < 4; j++)
                temp[i] = '\0';
    
            strncat(temp, paddedBin+(4*i), 4);
            printf("temp: %s\n", temp);
        }
    
        return NULL;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    paddedBin does not have enough space allocated to it for
    Code:
    strcat(paddedBin, binary);
    to succeed. Even with no padding, it would require strLength+1 just to hold binary itself, and the padding added only makes it worse.

  3. #3
    Registered User
    Join Date
    Sep 2009
    Posts
    11
    jesus christ. i hate myself.

    thanks so much.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21