-1

I'm programming in C and compiling with gcc. Every time I compile I get a stack smashing detected error. What does this mean and how can I fix it?

#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;
}
Jens
  • 69,818
  • 15
  • 125
  • 179
user2823747
  • 67
  • 2
  • 3
  • 10
  • In `scanf("%d %d %s", &penalty_points, &num_drop, &statGen);` you need to replace %s with %c as you are reading in a single character and not a string (char array). – George Mitchell Sep 27 '13 at 14:13
  • Also, in `getScore()`, you are not doing any validation on `position` to make sure it falls within the arrays. That's another crash waiting to happen, that your compiler generally won't help you catch... – twalberg Sep 27 '13 at 16:12

1 Answers1

6

You use %s with &statGen. The %s specifier is for a string; the corresponding argument must point to a buffer with enough space for the string, including a terminating null character. However, statGen is a single char.

To read just a single char, use "%c" instead of "%s". If you want to skip white space before the character, use " %c". The space asks scanf to skip white space.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312