Skip to content

Instantly share code, notes, and snippets.

@nigoroll
Last active February 22, 2022 15:35
Show Gist options
  • Select an option

  • Save nigoroll/e4d858155bc4e1f30891de6977a56d39 to your computer and use it in GitHub Desktop.

Select an option

Save nigoroll/e4d858155bc4e1f30891de6977a56d39 to your computer and use it in GitHub Desktop.
C modify temporary lifetime object
#include <stdio.h>
#include <assert.h>
struct A {
int b;
};
struct X {
int x;
struct A *a;
};
static void
foo(const char *n, struct X *x)
{
assert(x != NULL);
assert(x->a != NULL);
printf("%s = { .x = %d, .a = { .b = %d }}\n", n, x->x, x->a->b);
}
#define FOO(x) foo(#x, x)
void
main(void) {
struct X x = { .x = 1, .a = &(struct A){ .b = 2 }};
struct A a = { .b = 2 };
struct X y = { .x = 1, .a = &a};
FOO(&x);
/* ILLEGAL?
* 6.2.4 (8) "Any attempt to modify an object with temporary
* lifetime results in undefined behavior."
*/
x.a->b = 3;
FOO(&x);
/* --- */
FOO(&y);
/* should be legal */
y.a->b = 4;
FOO(&y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment