简体   繁体   中英

Attempting to access a value in a pointer location and getting a seg fault

So I'm getting a seg fault when I attempt to access a specific pointer in memory. I've pruned the code to what all i think is needed, but if I forgot something let me know.

char memoryPool[100000];
static const int HEADER_NEXT = 4;

char* firstHole;

void initializeManager(void)
{
    *( (void**)(memoryPool + HEADER_NEXT) ) = 0;

    std::cout << "setting header next: " << (char**)(block + HEADER_NEXT) << std::endl;

    firstHole = memoryPool;
}

int freeRemaining(void)
{
    int result = 0;
    char* block = firstHole;

    while( block != 0 )
    {
        result += *( (int*)(block + HEADER_SIZE) );
        std::cout << "running Result: " << result << std::endl;
        std::cout << "header next: " << (char**)(block + HEADER_NEXT) << std::endl;

        block = *( (char**)(block + HEADER_NEXT) ); // seg fault
    }

    return result;
}

here is the terminal output:

setting header next: 0x107e760e4
Entering freeRemaining
running result: 65536
header next: 0x107e760e4
Segmentation fault: 11
logout

So the addresses are identical but why can i access the value (0) stored at that address?

I think this is the problem:

while( block != 0 )

It should be

while( *block != 0 )

block is a pointer to memoryPool, its value should not become NULL but its content should be (since you set next header to 0 during your initialization)

EDIT:

block pointer update is wrong

block = *( (char**)(block + HEADER_NEXT) );
block = *( (char**)(CHAR_PTR + HEADER_NEXT) );
block = *( (char**)(CHAR_PTR) );

You are recasting a char pointer to a pointer of char pointer. It should be

block = (char*)(block + HEADER_NEXT);
block = block + HEADER_NEXT // without cast is even better
block += HEADER_NEXT // This one is good too
*( (void**)(memoryPool + HEADER_NEXT) ) = 0;

This statements and similar one in freeRemaining() look incorrect. What are you trying to do there? Also, the reason of you segfault is presumably the last assignment. block variable is supposed to point to some address in range of memoryPool, but from what I see, you're assigning a value from address 0x0000000.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM