gcc 4.4.3下C代码中的奇怪行为

str*_*oop 2 c

我今天遇到了这段代码,同时辅导一些C语言课程的学生.该练习要求实施两项职能.第一个扫描用户的输入,第二个显示先前扫描的内容.我遇到的代码如下:


#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);
}
Run Code Online (Sandbox Code Playgroud)

虽然这段代码充满了不一致,但它实际上在gcc 4.4.3下工作:它显示已经输入的数字!!!!!! 有谁知道这些代码是如何工作的?

非常感谢

nmi*_*els 8

如果这样可行,那就是纯粹的愚蠢运气.打印的内容myDisp是未初始化的堆栈,它可能包含也可能不包含放入类似命名变量的数据myInput.相关阅读

这是一个简单的方法来解决它无所事事的代码:

void myInput(int i,int n)
{
  // Add some variables to mess up the stack positioning.
  int breaker;
  int cpt;
  int stomper;
  int tab[n];
  int smasher;

  for ( cpt=0; cpt<n; cpt++)
  {
    printf("Enter a number :");
    scanf("%d",&i); 
    tab[cpt]=i;
   }

  // Trick the compiler into thinking these variables do something.
  breaker = 1;
  smasher = 3 * breaker;
  stomper = smasher + breaker;
  breaker = stomper * smasher;
 }
Run Code Online (Sandbox Code Playgroud)

打破它的另一种方法是printf在调用myInput和之间调用函数(比方说)myDisp.

  • 扩展:你可能会很幸运,`myDisp`在与其他函数相同的内存段中分配`tab`.它似乎工作,但代码不正确,需要修复. (3认同)