in reply to OT: Why does malloc always give me 24? [SOLVED]

What's the size of "int" on your system? It's nearly always best to use types with defined sizes, like int32_t.

Also, i can' exactly make sense of what you are trying to do here. You are only allocating a single element. My "memory managment in C" is quite rusty, but if you want an array with N elements of type acme, i think it should be more in the line of this:

#define N 10 typedef struct _acme { int data; } acme; acme *gizmo; gizmo* = (acme*)malloc(sizeof(acme) * N);

But as i said, it's been a long time and i wrote this from memory.

PerlMonks XP is useless? Not anymore: XPD - Do more with your PerlMonks XP
Also check out my sisters artwork and my weekly webcomics

Replies are listed 'Best First'.
Re^2: OT: Why does malloc always give me 24?
by etj (Priest) on Aug 18, 2024 at 16:36 UTC
    The answer to "why 24" will be that allocating a single byte, or 4, probably doesn't make sense with the amount of bookkeeping data involved. That malloc implementation is probably just making the minimum size be 24, quite possibly for alignment reasons.

    C99 has variable-length arrays (VLAs), which would allow this, where gizmo would be on the stack and evaporate on do_something's return:

    void do_something(int n) { struct acme gizmo[n]; int i; for (i=0; i<n; i++) { /* do stuff */ } }

    The code above has a syntax error: gizmo* = (acme*)malloc(sizeof(acme) * N) has an unnecessary "*" after "gizmo".