|
-
September 29th, 1999, 08:28 PM
#1
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
-
September 30th, 1999, 10:32 AM
#2
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
-
September 30th, 1999, 11:59 AM
#3
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!
-
September 30th, 1999, 12:17 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|