Pelles C forum

Pelles C => Bug reports => Topic started by: PaoloC13 on May 24, 2026, 04:24:16 PM

Title: array struct assignments
Post by: PaoloC13 on May 24, 2026, 04:24:16 PM
When I copy a returned struct { T arr[N]; } into the caller, it skips array elements whose value came from memset or ={0}. Only elements with explicit individual assignments are written.

typedef struct { float m[16]; } Mat4;

    Mat4 broken(void) {
        Mat4 s;
        memset(&s, 0, sizeof(s));   // set the block
        s.m[0] = 1.0f;              // explicit
        return s;
    }

    // Caller:
    Mat4 result;
    memset(&result, 0xCC, sizeof(result));   // fill with known garbage
    result = broken();

  /* Expected per C standard: result.m[1] == 0.0f           */
  /* Observed:                result.m[1] == -1.07374e+08   */
  /*   (the 0xCC garbage — the copy never wrote that slot)  */

Test: pre-fill the destination with a recognisable non-zero sentinel (0xCC bytes works well) before the call.
If any zero-expected field shows the sentinel value after the call, the copy skipped it.

My fix: explicitly assign every element of the array.
Is this a bug or a normal behaviour?
Title: Re: array struct assignments
Post by: TimoVJL on May 24, 2026, 05:08:29 PM
Think using static keyword
Mat4 broken(void) {
    static Mat4 s;
    memset(&s, 0, sizeof(s));   // set the block
    s.m[0] = 1.0f;              // explicit
    return s;
}
Title: Re: array struct assignments
Post by: Michele on May 24, 2026, 05:44:45 PM
You should never return an automatic variable.
's' is allocated on the stack, and is overwritten by other data when function exits.
You can declare it 'static' as suggested or define it in the caller and pass it.
Title: Re: array struct assignments
Post by: PaoloC13 on May 25, 2026, 12:00:54 AM
Regret. I have to go back to the beginners forum.
Title: Re: array struct assignments
Post by: John Z on May 25, 2026, 07:56:59 AM
Don't sweat it  :) many of us end up there every once in a while....


John Z