Search code examples
cmemoryscopeatmegaavr-gcc

Embedded memory allocation and scope


If I want to create a structure initialization functions that return a pointer to the initialized structure members, will the allocated memory to the data array in new_foo still be valid outside the function?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct structure{
    char* data;
    size_t num;
}foo_t;


foo_t* new_foo(size_t num);

int main(void){
    foo_t* foo = new_foo(32);
    while(1){;}
}

foo_t* new_foo(size_t num){
    foo_t* self;
    char temp[num];
    self->data = temp;

    self->num = num;

    return self;
}

I wanted to take a look at the assembly code to see if anything jumped out at me, the only thing that potentially makes me thing memory is still valid is that there are no stack operations associated with

char temp[num];
self->data = temp;

but it's been a while since I had to look at assembly code.

https://godbolt.org/z/5Wx4TY

[EDIT] Modified new_foo

foo_t* new_foo(size_t num){
    static foo_t self = {NULL, 0};
    char data_array[num];
    self.data = temp;

    self.num = num;

    return &self;
}

Solution

  • The function has undefined behavior.

    foo_t* new_foo(size_t num){
        foo_t* self;
        char temp[num];
        self->data = temp;
    
        self->num = num;
    
        return self;
    }
    

    For starters the pointer self is not initialized and has indeterminate value.

    The variable length array temp is a local variable of the function that will not be alive after exiting the function. So any pointer to it returned from the function will be invalid.