structure and union

This is a discussion on structure and union within the C Programming forums, part of the General Programming Boards category; My two questions regarding structures and union are: 1. Why does the following program results in segmentation fault. Code: #include<stdio.h> ...

  1. #1
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804

    structure and union

    My two questions regarding structures and union are:
    1. Why does the following program results in segmentation fault.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
    	union a
    	{
    		char ch[2];
    		int i;
    	};
    	union a key;
    	key.ch[0]='5';
    	printf("%d %d %d",key.ch[0],key.ch[1],key.i);
    	getch();
    }
    2. Why the output of the code 24.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
    	struct
    	{
    		char ch;// char 1 byte
    		int i;//int 4 bytes
    		float f;//float 4 bytes
    		double r;// double 8 bytes
    	}v;
    	printf("%d",sizeof(v));
    	getch();
    }
    I know slack byte thing but that should also result in 20bytes coz my PC's word size is 4 bytes(32bit OS).
    Thanks
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    If a double is 8-bytes, it must/should/will be placed so that it does lie on an 8-byte boundary.

    I can't answer the first because the question is itself false.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I agree with tabstop: First question should not cause a segfault as it is posted. If it does, I suspect you are either not actually running the code you posted [perhaps there is some minor syntax error, and you are running the old version that is different?]

    In the second case, you can't really know what the size of a struct will be without going into details of what compiler, what processor, and what settings the compiler is given. Any number from 15 and upwards is possible. In this case, we can infer that double has an alignment equal to it's size [this is very common] and that a 4 byte int will be aligned to 4 bytes [but it's not NECESSARILY always true that this is the case - a 16-bit compiler that uses 32-bit float and 64-bit double could also give the same size, just that there would be more bytes between the int and float element].

    Relying on size and offset of structures is very dangerous.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    602
    What do you believe the value of k.i should be? Yeah be cautious of any struct offset use. There was a thread to get to the values of structure members using a define macro of offset().

    Code:
       #define offsetof(st, m) ((size_t) ( (char *)&((st *)(0))->m - (char*)0))

  5. #5
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by matsp View Post
    I agree with tabstop: First question should not cause a segfault as it is posted. If it does, I suspect you are either not actually running the code you posted [perhaps there is some minor syntax error, and you are running the old version that is different?]
    --
    Mats
    I ran exactly the same code that's why I'm saying that it's producing run time error. The error is
    Run-Time Check Failure #3 - The variable 'key' is being used without being defined.
    By the way are segfault and run time error two different things? It might be the term 'segfault' that I used in my earlier post which is causing problem to you in understanding. I thought both segfault and run time error are same thing.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    The first one is wrong because you can only access the last member of a union that was set. You access key.i when you only set key.ch[0]. Furthermore, key.ch[1] also has an unspecified value because it was not initialized or assigned.

    The second should be printf("%zu",sizeof(v)); in C99 or, in C89, the best you can do is probably printf("%lu",(unsigned long)sizeof(v));, since all you know about size_t (the type returned by sizeof) is that it is an unsigned integer type.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > By the way are segfault and run time error two different things? It might be the term 'segfault' that I used in my earlier post which is causing problem to you in understanding.
    Yes, VASTLY different things - be specific next time.

    Had you posted the actual error message (not your faulty interpretation), we would have been all over it right away and you would have had your answer a day earlier.

    A segfault is an access (read or write) to memory which does NOT exist. Accessing NULL is one typical example.

    A run-time check is the code examining the program state as it goes. In this case, it looked at the variable in question and determined that you hadn't written to it before reading it.

    The words say it all really.
    The variable 'key' is being used without being defined.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    I will be more careful next time.
    But still why it says that the variable 'key' is is not defined. I think I've defined it here
    Code:
    union a key;
    Also when I change this line to
    Code:
    key.ch[0]='5';// to key.i=5; the code works properly
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  9. #9
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,662
    >> But still why it says that the variable 'key' is is not defined. I think I've defined it here

    That code should compile and run fine.

    EDIT: What you probably meant anyway was:

    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
    	union a
    	{
    		char ch[2];
    		int i;
    	};
    	union a key;
    	key.ch[0]='5';
    	printf("%c %c %d\d",key.ch[0],key.ch[1],key.i);
    	getch();
    }



    ITSA
    Socket Library!

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > But still why it says that the variable 'key' is is not defined. I think I've defined it here
    You only wrote key.ch[0]

    key.ch[1] was untouched, and key.i is basically junk (partially initialised by it's overlap with key[0]).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by Salem View Post
    > But still why it says that the variable 'key' is is not defined. I think I've defined it here
    You only wrote key.ch[0]

    key.ch[1] was untouched, and key.i is basically junk (partially initialised by it's overlap with key[0]).
    Thanks Salem for your very much helping reply. Now I get it what I was wrong with. Thanks.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  2. Why wont my function exit correctly?
    By LightsOut06 in forum C Programming
    Replies: 2
    Last Post: 10-09-2005, 09:23 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. problem with c and xml
    By dianazheng in forum C Programming
    Replies: 11
    Last Post: 05-26-2005, 07:10 PM
  5. Structure containing a union of more structures!
    By Bajanine in forum Windows Programming
    Replies: 2
    Last Post: 03-08-2003, 10:53 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21