Search code examples
c

Is this C structure assignment statement legal?


Here is a code example followed by my question:

#include <stdio.h>
#include <string.h>

struct st {

    char stringField[100];
    int intField;
};

typedef struct st st;

void test(st *parameterStruct)
{
    st localStruct;
    strcpy(localStruct.stringField, "HELLO");
    localStruct.intField = 5;

    *parameterStruct = localStruct;
}

int main()
{
    st myStruct;
    strcpy( myStruct.stringField, "XXX" );
    myStruct.intField = 9;

    printf("%s,%i\n", myStruct.stringField, myStruct.intField );

    test(&myStruct);

    printf("%s,%i\n", myStruct.stringField, myStruct.intField);

    return 0;
}

OUTPUT:

XXX,9
HELLO,5

I was thinking that since the structure 'localStruct' was created inside a function (NOT using malloc) it had local scope and thus the memory locations where it was stored were free to be overridden once the function stopped executing. However, I tried running this sample program and it executed with no issues. I was thinking that the second print statement was going to print gibberish to the screen since I assigned 'myStruct' to local variable 'localStruct' (versus 'localStruct' being dynamically allocated). I know if 'localStruct' had been created using malloc there would be no such issues.

My question: is assigning the structure variable 'myStruct' (a non dynamic local variable) to y by the use of a pointer in the function test okay and safe to do? I hope that the question is clear.


Solution

  • Assignment always copies.

    If you did something like *x = &y (assuming the types matched - if the parameter was declared as st** x, for example), you would be copying the address of y, but since y will go out of scope soon, that assignment would be unsafe, as you feared.

    But since you're doing *x = y instead (where the parameter is declared st* x), you are copying the content of y to *x, so even after y goes out of scope, the data stored in *x should be valid.