-
July 1st, 2014, 06:23 AM
#1
what's wrong with this program
The file1.c defines an array 'myarray' as,
int myarray[10];
The file2.c uses 'myarray' as,
extern int *myarray;
void foo()
{
myarray[0] = 10;
}
What kind of problem this program may have?
Thanks !
-
July 1st, 2014, 07:26 AM
#2
Re: what's wrong with this program
it'll work as long as you don't do something stupid. such as accessing elements out of the actual defined bounds. In that case "anything could happen".
if you defined it extern properly, the compiler could potentially spot an out of bounds access with a warning (assuming the index is calculable at compile time)
-
July 1st, 2014, 07:50 AM
#3
Re: what's wrong with this program
"accessing elements out of the actual defined bounds" would be a problem in general everywhere.
When you say, "if you defined it extern properly" what do you mean here ?
-
July 1st, 2014, 02:12 PM
#4
Re: what's wrong with this program
Originally Posted by mithlesh
What kind of problem this program may have?
Plenty. It's generally considered bad programming practice to have global data (state).
http://c2.com/cgi/wiki?GlobalVariablesAreBad
-
July 2nd, 2014, 04:01 AM
#5
Re: what's wrong with this program
Originally Posted by mithlesh
The file1.c defines an array 'myarray' as,
int myarray[10];
What is in that line of code? It is sizeof(int) * 10, which is probably 40 bytes (assuming int's are 4 bytes). Then this:
The file2.c uses 'myarray' as,
extern int *myarray;
What is in that code? it is sizeof(int*), which is probably 4 or 8 bytes. See the problem? So which one is right? You have two different values for sizeof(). If you now access myarray believing it can hold 10 ints, what if it can't hold 10 ints, but instead is only 4 (or 8) bytes in size? You now have a memory overwrite.
If you are to use extern, the proper way to use extern is to make sure you use the same type. An array is not a pointer:
is to be matched with:
Code:
extern int myarray[10];
Regards,
Paul McKenzie
Last edited by Paul McKenzie; July 2nd, 2014 at 04:08 AM.
-
July 9th, 2014, 08:21 AM
#6
Re: what's wrong with this program
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
|