JohnM
JohnM

Reputation: 1

Pointer is changing after function call, C

So I've written this program to represent a car park as a bitset, each space in the car park being one bit. I have a checkSpace function to check if a space is occupied or not and for some reason the pointer to my car park bitset changes or the data changes after I pass it into the function. To test it I set up the car park, I checked a space, then checked it again immediately after and for some reason the return value is changing when it shouldn't be. Any help would be appreciated!

    struct carPark{
        int spaces, levels;
        unsigned char * park;
    };

    struct carPark * emptyCarPark(int levels, int spaces){
        int chars = (spaces*levels)/8;
        if((spaces*levels)%8 != 0){
            chars++;
        }
        unsigned char park[chars];
        for (int i = 0; i < chars; ++i){
            park[i] = 0;
        }
        unsigned char * ptr  = &park[0];
        struct carPark * myPark = malloc(sizeof(struct carPark));
        myPark->park = ptr;
        myPark->spaces = spaces;
        myPark->levels = levels;
        return myPark;
    }

    int checkSpace(int level, int spaceNum, struct carPark * carpark){
        int charPosition = ((level*carpark->spaces) + spaceNum)/8;
        int bitPosition = ((level*carpark->spaces) + spaceNum)%8;
        if(carpark->park[charPosition]&&(1<<bitPosition) != 0){
            return 1;
        }
        return 0;
    }

    int main(int argc, char const *argv[]){
        struct carPark * myPark = emptyCarPark(5,20);
        printf("1st check: %d\n",checkSpace(1,1,myPark));
        printf("Second check: %d\n",checkSpace(1,1,myPark));
        return 0;
    }

So when I run the program I get:

    1st check: 0
    Second check: 1

Upvotes: 0

Views: 89

Answers (1)

Loring
Loring

Reputation: 322

Look at the code below - in emptyCarPark() you are allocating the park array on the stack, and then returning a pointer to it. As soon as the function returns, the park array is no longer allocated and you have a dangling pointer - for more information, see: Cause of dangling pointers (Wikipedia)

    unsigned char park[chars];
    for (int i = 0; i < chars; ++i){
        park[i] = 0;
    }
    // This is the pointer to an object on the stack.
    unsigned char * ptr  = &park[0];

    struct carPark * myPark = malloc(sizeof(struct carPark));
    myPark->park = ptr;

Upvotes: 1

Related Questions