gcc compiler dynamic array declaration without warning

I demonstrate for one of Prof Richard Bowden's modules on C programming for first year Electronic Engineering students. Recently one of the tasks given to students was read in a matrix, multiply and write it out. To start with they did 3x3 then 7x7 then were instructed to make it variable size.

So when going round to help I showed a few of them how to allocate deallocate dynamic memory then asked the question had they been taught this. Apparently at they hadnt by this point, later finding out it comes up after Christmas.

My ramblings today are not about the module content or structure but actually the gcc compiler. When learning to program in C++ I learnt on a fairly sensible compiler inside Visual Studio. Then hit the gcc compiler and got annoyed by stupid things, for example

Visual Studio interprets this fine

std::vector<std::vector<int>>

g++

Error, required:

std::vector<std::vector<int> >

To note the space between the last two angle brackets.

While walking round I saw some students code and got a little scare by it they performed operations such as:

 

int size = 0;

scanf("%i",size);

int myArray[size];

for (int i = 0 ; i < size ; i++)

scanf("%f",myArray[i]);

for (int i = 0 ; i < size ; i++)

printf("%f",myArray[i]);

 

To my horror this compiled without warning or error and even worse it worked. I later while chatting to friends found that this was normal for the gcc compiler, and apparently the g++. So therefore we had some guesses about how this would work and the common answer was:

myArray is initialised to length 0, then since taken of the stack when read and written to you corrupted the stack.

The message to take away from this horror story of teaching C, is two things use a compiler that may not follow the letter of the standard but actually is intelligent and knows what you mean; always use -wall when compiling on gcc otherwise you will end up in a pile of mess later on!

Wednesday, December 14, 2011 10:48:00 AM Categories: C Programming
Stuart James

Comments

Tuesday, February 7, 2012 2:15:02 PM

re: gcc compiler dynamic array declaration without warning

I appreciate, cause I found exactly what I was looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye 8(

Thursday, February 9, 2012 8:50:21 AM

re: gcc compiler dynamic array declaration without warning

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

Monday, February 13, 2012 7:38:08 AM
unknown

re: gcc compiler dynamic array declaration without warning

Thanks for taking the time to share this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely useful for me.

Comments are closed on this post.