Click to See Complete Forum and Search --> : a generous compiler ?


Zerg
September 29th, 1999, 08:28 PM
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

Sivakumar
September 30th, 1999, 10:32 AM
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

shiva@indusaglobal.com



Programming is always a learning process

September 30th, 1999, 11:59 AM
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!

Paul McKenzie
September 30th, 1999, 12:17 PM
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