J
John Reye
1)
a = i++;
http://c-faq.com/expr/evalorder1.html
So this attempt at optimisation is wrong:
int i;
int a[10];
for (i = 0; i < sizeof(a); )
a = i++; /* set a to {1, 2, 3, ...} */
Correctly optimized, it should be:
for (i = 0; i < sizeof(a); )
i = a = i+1; /* set a to {1, 2, 3, ...} */
2)
int i;
char b[10];
(int *)b = i;
Alignment problem. There is not guarantee that b is so aligned, that
it's address satisfies alignment-requirements, which an int-pointer
would need (such as even address, or maby "address divisible by 4", or
whatever it happens to be)
3)
struct
{
char a;
int b;
} mystruct;
// set byte at lowest address within b to 0x12;
char *p = &mystruct;
p[1] = 0x12;
Bug: struct padding was forgotten. There will probably be some padding
between a and b, so that b is aligned for good memory-access.
Rather use:
*((char *)&mystruct.b) = 0x12;
Or:
struct
{
char a;
union {
int b;
char c;
};
} mystruct;
mystruct.c = 0x12
Would this union work on every platform??
Which undefined behaviour (or other bugs) do you think is interesting
to know about?
Thanks.
a = i++;
http://c-faq.com/expr/evalorder1.html
So this attempt at optimisation is wrong:
int i;
int a[10];
for (i = 0; i < sizeof(a); )
a = i++; /* set a to {1, 2, 3, ...} */
Correctly optimized, it should be:
for (i = 0; i < sizeof(a); )
i = a = i+1; /* set a to {1, 2, 3, ...} */
2)
int i;
char b[10];
(int *)b = i;
Alignment problem. There is not guarantee that b is so aligned, that
it's address satisfies alignment-requirements, which an int-pointer
would need (such as even address, or maby "address divisible by 4", or
whatever it happens to be)
3)
struct
{
char a;
int b;
} mystruct;
// set byte at lowest address within b to 0x12;
char *p = &mystruct;
p[1] = 0x12;
Bug: struct padding was forgotten. There will probably be some padding
between a and b, so that b is aligned for good memory-access.
Rather use:
*((char *)&mystruct.b) = 0x12;
Or:
struct
{
char a;
union {
int b;
char c;
};
} mystruct;
mystruct.c = 0x12
Would this union work on every platform??
Which undefined behaviour (or other bugs) do you think is interesting
to know about?
Thanks.