Find the answer to your Linux question:
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 ...
  1. #1
    Just Joined! amit4g's Avatar
    Join Date
    Feb 2007
    Location
    Bangalore,India
    Posts
    63

    Unhappy 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

  2. #2
    Linux 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:

    Code:
    printf("%d\n",*(p->u.num));
    P.S. If you use code tags, your code will be much easier to read.

  3. #3
    Linux Guru Rubberman's Avatar
    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!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...