I came across this piece of code today while tutoring some students in a C programming language course.
The exercise asked to implement two functions. The first one scans input from a user and the second displays what has been previously scanned.
The code I came across is the following:
#include <stdio.h>
void myInput(int i,int n)
{
int cpt;
int tab[n];
for ( cpt=0; cpt<n; cpt++)
{
printf("Enter a number :");
scanf("%d",&i);
tab[cpt]=i;
}
}
void myDisp (int n)
{
int tab[n];
int cpt;
for ( cpt=0; cpt <n; cpt++)
{
printf("%d ", tab[cpt]);
}
}
int main()
{
int n; int i;
printf(" Entrer the numbers of elements you want: \n");
scanf("%d \n",&n);
int tab[n];
myInput(i,n);
myDisp(n);
}
Although this code is full of inconsistencies, it does actually work under gcc 4.4.3: it displays the numbers that have been input!!!!!!
Does anyone understands how come these code works?
Thanks very much
If that works, it’s through sheer dumb luck. What is printed in
myDispis uninitialized stack, which may or may not contain the data that was put into similarly named variables inmyInput. Related readingHere’s an easy way to break it with do-nothing code:
Another way to break it would be to put a function call (say, to
printf) between the calls tomyInputandmyDisp.