Re: Question on accessing structure



On Jan 31, 1:52 pm, Sid <Sid4C...@xxxxxxxxx> wrote:
All,
See the below piece of C code snippet

typedef struct _a
{
int ia;
int ja;

}A;

typedef struct _b
{
int ib;
int jb;

}B;

typedef struct _x
{
A a;
B b;

}X;

void func(X *ptr)
{
ptr->b.ib = 10;
ptr->b.jb = 20;
ptr->a.ia = 48;
ptr->a.ja = 50;

}

main()
{
A *temp = (A*)malloc(sizeof(A));
func(temp);
printf("%d\n",((X*)temp)->b.ib);

}

why does not the above program result in segmentation error.
Because it invokes undefined behavior, you pass a pointer to A where a
pointer to X is expected.
I am just allocating memory for structure A and typecasting it to
structure X and writing value to its members i.e Structure A and
structure B.
I compiled above program with MS VC++ and gcc ...it just gives me
warning and not runtime error as well.....and o/p is right.....
Your program most likely writes to memory you have access to, but as
far as C is concerned, you invoke undefined behavior and anything can
happend after that.

.



Relevant Pages

  • Re: link pointer access problem
    ... int b_value; ... be a null pointer ... dereference a pointer with an indeterminate value. ...
    (comp.lang.c)
  • Re: error from mfilename
    ... typedef struct tagTRANSMITTER_CONFIGURATION ... PCIBIRD_API int InitializeBIRDSystem; ... Parameters Passed: USHORT sensorID, ...
    (comp.soft-sys.matlab)
  • [PATCH 1/2] Char: nozomi, Lindent the code
    ... +static const int nzdebug = 0; ... u8 port; ...
    (Linux-Kernel)
  • [LONG] help with old source code from book
    ... int cols, int magic_number); ... scale = 1.0; ... reads mesh data into a mesh structure * ...
    (comp.lang.c)
  • Re: access violation
    ... I didn't find any access violation on running your code in VC 6.0 compiler. ... typedef struct tagTIMESTAMP_STRUCT ... unsigned int fraction; ... > unsigned char u8; ...
    (microsoft.public.vc.language)