Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

On-heap struct pointer assignment corrupts memory #164

Open
ChAoSUnItY opened this issue Nov 11, 2024 · 1 comment
Open

On-heap struct pointer assignment corrupts memory #164

ChAoSUnItY opened this issue Nov 11, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@ChAoSUnItY
Copy link
Collaborator

Considering the following example minimum arena implementation:

#include <stdlib.h>

typedef enum {
    A,
    B
} type_t;

typedef struct {
    type_t typ;
} data_t;

typedef struct {
    int cap;
    int size;
    data_t *data;
} arena_t;

arena_t *arena_init(int cap) {
    arena_t *arena = malloc(sizeof(arena_t));
    arena->cap = cap;
    arena->size = 0;
    arena->data = calloc(cap, sizeof(data_t));
    return arena;
}

data_t *arena_alloc(arena_t *arena) {
    if (arena->size + 1 >= arena->cap)
        return NULL;

    return &arena->data[arena->size++];
}

void arena_free(arena_t *arena) {
    free(arena->data);
    free(arena);
}

int main() {
    arena_t *arena = arena_init(1024);
    data_t *data = arena_alloc(arena);
    printf("%d\n", arena->data);
    data->typ = B;
    printf("%d\n", arena->data);
    arena_free(arena);

    return 0;
}

I expect that it would output 2 numbers that refers to same memory address where arena->data resides, however, using shecc results in the second number is different to the first one, and same as the integer value of enum B previously assigned.

Using gcc to compile this program would have expected result however.

@ChAoSUnItY ChAoSUnItY added the bug Something isn't working label Nov 11, 2024
@ChAoSUnItY
Copy link
Collaborator Author

ChAoSUnItY commented Nov 11, 2024

Additional note, this seems to not be only affecting by enum, in fact, all types which resides in the first member of struct would cause same behavior.

This doesn't affect if the array is allocated outside of a struct on heap, the following code works as expected:

#include <stdlib.h>

typedef enum {
    A,
    B
} type_t;

typedef struct {
    type_t typ;
} data_t;


int cap = 1024;
int size = 0;
data_t *data;

int main() {
    data = calloc(cap, sizeof(data_t));
    data_t *local_data = &data[size++];
    printf("%d\n", data);
    local_data->typ = A;
    printf("%d\n", data);
    free(data);

    return 0;
}

@ChAoSUnItY ChAoSUnItY changed the title Enum member in-struct generation corrupts memory On-heap struct pointer assignment corrupts memory Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant