Results 1 to 3 of 3
This is a pseudo code from a much bigger data structure i'm using, To replicate the issue, mentioned below is similar issue i'm facing with my real problem. Can someone ...
- 07-13-2010 #1
Data structure: Error with Accessing member
This is a pseudo code from a much bigger data structure i'm using, To replicate the issue, mentioned below is similar issue i'm facing with my real problem. Can someone please help me on this ?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student
{
int age;
union eng{
int *num;
}u;
};
typedef struct student STD;
int main(void)
{
STD *p = (STD *)malloc(sizeof(STD));
if ( NULL == p) {
printf("Not enough memory\n");
exit (1);
}
p->u.num = (int *)malloc(20);
memset(p->u.num,0x1,10);
printf("%d\n",*(p->u.num));
return 0;
}
[root@localhost .prog]# gcc -Wall -Werror -o union union.c
[root@localhost .prog]# ./union
16843009 <------ ???
~amit
- 07-13-2010 #2Linux Newbie
- Join Date
- Mar 2010
- Posts
- 121
memset(p->u.num, 0x1, 10) will set the first ten bytes at p->u.num to be 1. If int is four bytes on your system, that results in setting p->u.num to 0x01010101, which is 16843009. For example, using the following printf at the end of your code demonstrates that all individual bytes are 1:
P.S. If you use code tags, your code will be much easier to read.Code:printf("%d\n",*(p->u.num));
- 07-14-2010 #3Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
You are treating your int type as a 2 byte value, but an int in most systems these days is 32 bits (4 bytes), so malloc(20) is allocating only 5 integers of data. Also memset(p->u.num, 0x1, 10) is only setting the first 10 bytes (1/2) of the data allocated. As a result, I have to say that this is all very bogus and must ask if this is a class project?
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!


Reply With Quote