CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 1999
    Location
    Pacific Ocean, Deep Blue Sea
    Posts
    133

    a generous compiler ?

    can some1 tell me why i don't have to malloc for the struct ?
    thanks

    struct A {
    int a ;
    int b ;
    } ;

    int bbb(struct A *A_struct) {
    (A_struct[0]).a = 6543 ;
    (A_struct[4]).a = 6666 ;
    return 0 ;
    }
    int main() {
    struct A *A_struct ;

    bbb(A_struct) ;
    printf("a is %d\n",(A_struct[0]).a) ;
    printf("a is %d\n",(A_struct[4]).a) ;
    return 0 ;
    }

    result : a is 6543
    a is 6666



    Signature (up to 100 characters) You may use Markup in your signature

  2. #2
    Join Date
    Sep 1999
    Location
    Jamaica
    Posts
    138

    Re: a generous compiler ?

    This is why C or C++ is peculiar?

    Actually the program written by you should give a run time error because data cannot be stored without allocating the memory.

    In this case, the pointer is created for the structure but it is not initialised with NULL. So, the compiler has a junk address as the value and the data for the strucure is stored in the junk address.

    This is the reason why C is powerful and powerless.

    Regards

    Shiva

    [email protected]



    Programming is always a learning process

  3. #3
    Guest

    Re: a generous compiler ?

    Furthermore:

    1) The junk address may not always be the same, so if you run it over and over it may crash on you.

    2) It is important to note that you are writing to memory that you don't know - memory that could be used for other variables in your program, or it could even be code - this could introduce a really nasty crash that is hard to isolate, or it could just change some variables values, so your program won't crash but will still not work.

    Don't do it, my friend!



  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: a generous compiler ?

    You do have to malloc for the struct! You are overwriting memory. Coding such this will place you on the unemployment line very fast!

    You've discovered that just because you are doing illegal accesses, the program *may* run. However, if you were to run the program on another machine, your program will choke, if not now, then later.

    Regards,

    Paul McKenzie


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured