Search code examples
cif-statementpointerscompiler-errorsdereference

Why can't access struct pointer outside of function


Describe Issue: I'm able to access buffer variable inside of malloc function and can retrieve and set data with no issues

any attempt to access *(buffer+ insert some index here)->data outside of malloc function results in following error

mem* demo = malloc(2);
if(*(demo+1)->data == 0x00) {
... do some stuff here 
}

following error is produced by gcc cross compiler

kernel.c:96:21: error: invalid type argument of '->' (have 'int')
   96 |         if(*(demo+1)->data == 0x00) {

Code:

//Licensed under public domain
//also please note there is no standart library this is on a embedded system

typedef struct{
    _Bool allocated;
    unsigned char data;
} mem;
mem memory[1000];

mem* malloc(size_t size){
    mem* buffer[size];
    unsigned int successfulCounts = 0;
    unsigned int bufferCounter = 0;
    for(unsigned int i = 0; i < sizeof(memory); i++){
        //Hey that's available memory for us
        if(memory[i].allocated == 0){
            //because buffer is 16 4 items in memory (16*4)-15*4 can be found like this
            if(successfulCounts < sizeof(buffer)-sizeof(buffer-1)){
                *(buffer+successfulCounts) = &memory[i];
                successfulCounts++;
                memory[i].allocated = 1;
            }else{
                break;
            }
        }
    }
    return buffer;    
}


//... some more code that implements stuff like free() and calloc()

Odd Findings:

when mem * in function changed to unsigned char and returned *(buffer+1) i can access the data for some odd reason and i can get the exact same data i have pushed nothing is corrupted as i expect for some odd reason


Solution

  • This if statement

    if(*(demo+1)->data == 0x00) {
    

    is equivalent to

    if( *( ( demo + 1 )->data ) == 0x00) {
    

    but data is not a pointer. It has the type unsigned char

    typedef struct{
        _Bool allocated;
        unsigned char data;
    } mem;
    

    It seems you mean

    if( (demo+1)->data == 0x00) {
    

    Pay attention to that the function in any case is invalid

    mem* malloc(size_t size){
        mem* buffer[size];
        //...
        return buffer;    
    }
    

    For starters the return type of the function is mem * while the type of the returned expression is mem **. And moreover the function returns a pointer to a local object (array). So the returned pointer will not be invalid because the array will not be alive after exiting the function.