-
Segmentation Fault Error
I have been trying to compile this program to decode a message using arrays. However I have this error that I don't know how to fix: Segmentation fault(core dumped). Does anyone know what in my code is causing this?
Code:
#include <stdio.h>
#define MAX 53
FILE *mf, *cf;
void getCode(char code[]);
int getMessage(int msg[]);
void sortMessage(int msg[],int msgSize);
void decodeMessage(char code[], int msg[],int msgSize);
int main(void)
{
char code[MAX];
int msg[MAX];
int msgSize;
getCode(code);
msgSize = getMessage(msg);
sortMessage(msg, msgSize);
decodeMessage(code, msg, msgSize);
return 0;
}//end main
void getCode(char code[]){
fopen_s(&cf, "codefile.txt", "r");
fgets(code, MAX, cf);
fclose(cf);
}//end get_code
int getMessage(int msg[]){
fopen_s(&mf, "msgfile.txt", "r");
int i;
while(!feof(mf))
fscanf_s(mf, "%d\n", &msg[i++]);
return i;
fclose(mf);
}//end get_msg
void sortMessage(int msg[],int msgSize){
//Sort message
int j, i, temp;
for(i = 1; i < msgSize; i++)
{
temp = msg[i];
j = i - 1;
while(j >= 0 && temp < msg[j]){
msg[j+1] = msg[j];
j = j - 1;
}//end while
msg[j+1] = temp; //reset the contents into msg.
}//end for loop
}//end sort_msg
void decodeMessage(char code[], int msg[],int msgSize){
//Prints decoded message.
int i;
for(i = 0; i < msgSize; i++)
printf("%c", code[msg[i] % 100]);
printf("\n");
}//end decode_msg
-
> int i;
This is uninitialised, so when you use it to access an array, who knows what happens.
> while(!feof(mf))
See the FAQ for why using feof() to control a loop is bad.
> fscanf_s(mf, "%d\n", &msg[i++]);
You should avoid using the Microsoft-specific _s (supposedly "safe") versions of these functions.
They won't protect you from doing stupid things if you don't know how to use them to begin with, and they just lock you into their compiler.
If you're worried by some "deprecated" warning, we can tell you how to avoid that.
> return i;
OK...
> fclose(mf);
But you don't close the file, since you already returned.
-
Thank you sooo much! I just fixed what you told me and it works. I can't believe I was stuck on this for so long.