c++ - Access violation reading location fprintf -


so here teacher asked do:

create file store user typing. trouble im having , exception thrown , no error given me. first problem characters inside text file default in caps (without caps verification). second error happens press key (if theres cap verification).

#include <direct.h> #include <fstream> #include <stdlib.h>   using namespace std;  //function write file int save(int _key, char *file, bool caps); int backspace(); bool caps = false;  int main() {     char i;      while (true) {         (i = 8; <= 255; i++) {             // checks if key or down             if (getasynckeystate(i) == -32767) {                 //get caps lock state                 if ((getkeystate(vk_capital) & 0x0001) != 0) {                     //caps lock on                     caps = true;                     save(i, "c:/users/mycomputer/documents/school/c++/input.txt", caps);                 }                 else {                     //caps lock off                     caps = false;                     save(i, "c:/users/mycomputer/documents/school/c++/input.txt", caps);                 }             }         }     }     return 0; }  int save(int _key, char *file, bool caps) {     sleep(10);     file *output_file;     output_file = fopen(file, "a+");   switch (_key) {       case vk_return:          output_file = fopen(file, "a+");          fprintf(output_file, "%s", "\n");          break;       case vk_lbutton || vk_rbutton:          output_file = fopen(file, "a+");          fprintf(output_file, "%s", "");          break;       default:          if (caps == true) {              char = tolower(putchar(_key));              output_file = fopen(file, "a+");              fprintf(output_file, "%s", i);          }          else {              char = toupper(putchar(_key));              output_file = fopen(file, "a+");              fprintf(output_file, "%s", i);          }  }  fclose(output_file);   return 0; } 

segmentation fault

there several problems code. main issue, causing segmentation error

        fprintf(output_file, "%s", i);   // ouch !!! 

"%s" tells fprintf() find argument pointer array of characters. cross-check format string here. unfortunately, provide integer between 8 , 255. causes undefined behavior.

to correct error change to:

        fprintf(output_file, "%c", i); 

other issues

the fopen() call inside switch redundant: file opened before. it's no use open file without having closed before.

the function documentation tells least , significant bit, nothing bits in-between. check should be:

 if (getasynckeystate(i) & 0x8000 )   // not strict equality 

Comments