user265767
user265767

Reputation: 559

Binary operation, need help

I am about to create a function for a program, this is part of a program and is meant to be a bitmap that holds controls of which memory address is free for use (this has nothing to do with this function to do). The bitmap is bit[64] which holds 8 x 64 bits, the function under is taking a parameter number that is the number of data blocks the function should occupy. In array data_blocks[] should the number to the data block that has bit value 0(free).

Execution of this program gives some strange outputs, and data_blocks[] gives values beyond the length of 512. Can someone please give me a hand? Thanks

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

void occupyDataBlocks(int number)
{

    int ab = number;

    char bit[512/8];

    int bitNum = 0;

    int count;

    int data_blocks[ab];

    int b;

    for(bitNum = 0; bitNum < (sizeof(bit)/sizeof(char)); bitNum++) {
        char x = bit[bitNum];

        for(count = 0; x != 0; x >>= 1 ) {
            if(!(x & 0)) {
                data_blocks[count] = count;
            }

            if(count == number) {
                break;
            }
            count++;
        }
        if(count == number) {
            break;
        }
    }

    if(count == number) {
        int a;

        for(a = 0; a < 5; a++) {
            printf("%d\n", data_blocks[a]);
        }

    } else {
        printf("Not enough data blocks\n");
    }
}

int main(void)
{
    occupyDataBlocks(3);

    return 1;
}

Upvotes: 1

Views: 100

Answers (1)

Eugene Smith
Eugene Smith

Reputation: 9398

k, where to start ...

1) "sizeof(char)" is most likely 1. So you have a 512-byte array, not a 64-byte array.

2) "bit" array is not initialized.

3) the assignment "char x = bit[bitNum]; " should occur inside the loop.

4) "strlen(bit)" does not do what you think it does. It interprets "bit" as a text string. You probably want do use "sizeof(bit)/sizeof(char)".

5) "(x & 0)" always evaluates to 0. What are you trying to do? If you're trying to test the bit, you want to do "!(x & 1)".

6) "int data_blocks[number]": does this even compile? You can't allocate a local array like that if its size is not known at compile time.

7) if(count == number) { break; }

only breaks you out of the inner loop. The outer loop continues on uninterrupted.

8) Do you really want to reset "count" to 0 every iteration of the outer loop? Do you want the code to find 3 free locations somewhere in the array, or 3 free locations in a single byte?

Upvotes: 2

Related Questions