【问题标题】:I keep getting the error "stack smashing detected" [duplicate]我不断收到错误“检测到堆栈粉碎”[重复]
【发布时间】:2013-10-03 21:00:09
【问题描述】:

我正在使用 C 编程并使用 gcc 进行编译。 每次编译时,我都会收到一个堆栈粉碎检测到的错误。 这是什么意思,我该如何解决?

#include <stdio.h>

#define MAX_ARRAY 50


static int getScore(int assignmentNum[], int weight[], int daysLate[], float score[]){

  int position, tempWeight, tempLate;
  float tempScore;

  scanf("%d %f %d %d", &position, &tempScore, &tempWeight, &tempLate);
  score[position] = tempScore;
  weight[position] = tempWeight;
  daysLate[position] = tempLate;
  assignmentNum[position] = position;
  return weight[position];
}


int main(void){

  int penalty_points,  num_drop, num_assignment;
  static int assignmentNum[MAX_ARRAY], daysLate[MAX_ARRAY], weight[MAX_ARRAY];
  static float score[MAX_ARRAY];
  char statGen;
  int total = 0;

  scanf("%d %d %s", &penalty_points, &num_drop, &statGen);
  printf("%d\n", penalty_points);

  while (total <  100) {
    total = total + getScore(assignmentNum, weight, daysLate, score);
  }    
  return 0;
}

【问题讨论】:

  • scanf("%d %d %s", &amp;penalty_points, &amp;num_drop, &amp;statGen); 中,您需要将 %s 替换为 %c,因为您正在读取单个字符而不是字符串(字符数组)。
  • 另外,在getScore() 中,您没有对position 进行任何验证以确保它在数组中。这是另一个等待发生的崩溃,您的编译器通常不会帮助您捕获...

标签: c stack-smash


【解决方案1】:

您将%s&amp;statGen 一起使用。 %s 说明符用于字符串;相应的参数必须指向一个为字符串提供足够空间的缓冲区,包括一个终止空字符。但是,statGen 是单个 char

要仅读取单个char,请使用"%c" 而不是"%s"。如果要跳过字符前的空格,请使用" %c"。空格要求scanf 跳过空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2014-01-24
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多