S
Sourcerer
Does any of the following constitute undefined behavior? Once I allocate memory,
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}
--
"It is easy in the world to live after the world's opinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}
--
"It is easy in the world to live after the world's opinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/