Struziu Struziu - 1 month ago 15
C Question

Simple program crashes after using switch - C

I just have written a program which suppose to return char which appears the most/least. Program work during the testing without switch statement, but when I added it start to crash. Can you have a look?


Main function


#include <stdio.h>
#include <stdlib.h>
#include "tools.h"

int main(int argc, char *argv[]) {
int count[256] = { 0 };
int c;
while ( (c=getchar())!=EOF ){
count[c]++;
}
switch (argv[1][1]) {
case 'm': case 'M':
mostOften(count);
break;
case 'l': case 'L':
leastOften(count);
break;
default:
mostOften(count);
break;
}
return 0;
}



Tools function


#include <stdio.h>
#include <stdlib.h>
#include "tools.h"

void mostOften(int *s) {
int j;
int max, cha;
for(j=32; j<126; j++){
if(s[j]>max) {
max=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, max);
}

void leastOften(int *s) {
int j;
int min=10000, cha;
for(j=32; j<126; j++){
if(s[j] && s[j]<=min) {
min=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, min);
}

Answer

You are using max uninitialized, thus, reading garbage:

int max, cha;
for(j=32; j<126; j++){
    if(s[j]>max) {

Also, you need to check if argv[1][1] exists before using it:

switch ((argc > 1 && argv[1][0]) ? argv[1][1] : 0) {