News:

Download Pelles C here: http://www.pellesc.se

Main Menu

array struct assignments

Started by PaoloC13, Yesterday at 04:24:16 PM

Previous topic - Next topic

PaoloC13

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?

TimoVJL

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;
}
May the source be with you

Michele

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.

PaoloC13

Regret. I have to go back to the beginners forum.

John Z

Don't sweat it  :) many of us end up there every once in a while....


John Z