2015-01-13 2 views
0

я лицо сРезьба1: EXC_BAD_ACCESS (код = 1, адрес = 0x0) в С

Резьба1: EXC_BAD_ACCESS (код = 1, адрес = 0x0)

всякий раз, когда я пытаюсь сканировать строка от ввода до переменной char *. Я понятия не имею, почему это происходит, потому что все кажется правильным.

#include <stdio.h> 
#include <string.h> 
#include <time.h> 
#include <stdlib.h> 

заголовки

struct date { 
    int year; 
    int month; 
    int day; 
}; 

Дата sructure

struct patientData { 
    unsigned int code; 
    char name[11]; 
    char family[21]; 
    unsigned int age; 
    char MF; 
    char disease[11]; 
    unsigned int numOfVisits; 
    struct date *date1; 
    struct date *date2; 
    struct date *date3; 
    struct patientData *nextPtr; 

}; 

Пациент структуры данных

int isEmpty (struct patientData *sPtr); 
void visit (struct patientData **returned , unsigned int code); 
void Insert (struct patientData **sPtr, unsigned int code , char *name , char *family , unsigned int age ,char gender, int tmgh); 
void insertDisease (struct patientData **sPtr , char *name , char *family , char *disease); 
struct patientData *searchCode (struct patientData **sPtr , unsigned int code, int *returnval); 
struct patientData *searchName (struct patientData **sPtr , char *name , char *family); 
void searchDate (struct patientData **sPtr , int year , int month , int day); 
void delete (struct patientData **sPtr ); 
void report (struct patientData **sPtr ); 

функции; здесь (основная), где возникает проблема.

int main() { 

    char *choice; 

    unsigned int code; 
    char name[11]; 
    char family[21];; 
    char disease[11]; 
    int searchCodeReturnValue; 
    unsigned int age; 
    char gender; 
    int tmgh; 
    int year , month , day; 

    struct patientData *startPtr = NULL; 


    puts("Enter one of the following options:"); 
    puts("Visit"); 
    puts("InsertDisease"); 
    puts("search"); 
    puts("Delete"); 
    puts("END"); 

    scanf("%s",choice); 
    while (strcmp(choice, "END") != 0) { 
     if (strcmp(choice, "Visit") == 0) { 
      printf("Enter the code:\n"); 
      scanf("%5ui",&code); 
      struct patientData *a = searchCode(&startPtr,code,&searchCodeReturnValue); 
      if (searchCodeReturnValue == 1){ 
       visit(&a , code); 
      } 
      else if (searchCodeReturnValue == 0){ 
       printf("Enter name:\n"); 
       scanf("%10s",name); 
       printf("Enter family:\n"); 
       scanf("%20s",family); 
       printf("Enter age:\n"); 
       scanf("%ui",&age); 
       printf("Enter gender:\n"); 
       scanf("%c",&gender); 
       printf("Enter num of last visits:\n"); 
       scanf("%i",&tmgh); 
       Insert(&startPtr , code , name , family , age , gender , tmgh); 

      } 
     } 
     else if (strcmp(choice, "InsertDisease")== 0) { 
      printf("Enter name:\n"); 
      scanf("%10s",name); 
      printf("Enter family:\n"); 
      scanf("%20s",family); 
      printf("Enter disease:\n"); 
      scanf("%10s",disease); 
      struct patientData *namesearch = searchName(&startPtr, name, family); 
      insertDisease (&namesearch , name , family , disease); 
     } 
     else if (strcmp(choice, "Search")== 0) { 
      puts("Choose the way you wanna search: \n 1- by code \n 2- by first and last name \n 3- by Date"); 
      int choiceNum; 
      scanf("%i",&choiceNum); 
      if (choiceNum == 1) { 
       printf("Enter the code:\n"); 
       scanf("%5ui",&code); 
       searchCode(&startPtr, code , &searchCodeReturnValue); 
      } 
      else if (choiceNum == 2){ 
       printf("Enter name:\n"); 
       scanf("%10s",name); 
       printf("Enter family:\n"); 
       scanf("%20s",family); 
       searchName(&startPtr ,name , family); 
      } 
      else if (choiceNum == 3){ 
       printf("Enter year:\n"); 
       scanf("%i",&year); 
       printf("Enter month:\n"); 
       scanf("%i",&month); 
       printf("Enter day:\n"); 
       scanf("%i",&day); 
       searchDate(&startPtr , year , month , day); 
      } 
      else 
       puts("Wrong entry"); 
     } 
     else if (strcmp(choice, "delete")== 0) { 
      delete(&startPtr); 
     } 
     else if (strcmp(choice, "Report") == 0) { 
      report(&startPtr); 
     } 
     else if (strcmp(choice, "END") == 0) 
      return 0; 

     else{ 
      puts("wrong!"); 
      return 0; 
     } 
    } 
    return 0; 
} 

ответ

0

Вы разыменование неверного указателя, choice не объявлен как char указателя и не инициализируется, вам не нужно быть char указатель, может объявить choice как char массива тоже самая длинная строка она будет содержать, как представляется, "InsertDisease", который имеет 13 символов, объяви choice таким образом

char choice[14]; 

и изменить scanf к

scanf("%13s", choice); 

таким образом предотвратить переполнение буфера, и утечка памяти тоже (, которая будет вызвана с помощью malloc, если вы не правильно freechoice позже).

Я вижу, что вы не отсканировать для choice стоимости, которая сделает ваш цикл бесконечен, вы должны добавить это в верхней части петли, и удалить ее из цикла, а затем написать цикл, как

while (1) { 
    scanf("%13s", choice); 
    . 
    . 
    /* check the content of choice with strcmp and process the requested command */ 
    . 
    . 
} 

в цикле у вас есть if (strcmp(choice, "END") == 0) return 0;, чтобы он позаботился о завершении цикла.

0
char *choice; 

память не выделяется указатель, и вы делаете

scanf("%s",choice); 

Выделяет память к указателю, а затем попытаться проверить значение его.

choice = malloc(30); /* Size can be anything of your wish */ 

Таким образом, вы получаете доступ к неинициализированному указателю, который приведет к неопределенному поведению.

После этого с помощью этой памяти вам нужно освободить его

free(choice); 
+0

действительно? но я использовал этот стиль раньше, и у меня никогда не было такой ошибки, почему для этого требуется выделение памяти? '#include int main() { char * mine; scanf ("% s", мое); printf ("% s \ n", мой); return 0; } ' – user21087

+0

@ user21087 Да, чтобы сохранить ваше значение в какой-то ячейке памяти, вам необходимо выделить выделенную память. Вы можете сделать то же самое, используя 'malloc()', как показано – Gopi

Смежные вопросы