Segmentation Error in C program When Run

2019-09-14 10:55发布

I've tried malloc, and no malloc and it will build but not run or compile. When I run the code on codepad.org it gives me a segmentation error. I have an array of structures I'm inputting and I'm searching through them for a specific item. That's as far as I got and no compile. The code is as follows (I used netbeans, codeblocks, and visual basic 2012 programs):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
#define BLOODTYPESIZE 4
#define MAX 120000

typedef struct {
    int month;
    int day;
    int year;
} dateT;

typedef struct {
    int hour;
    int minute;
} timeT;

typedef struct {
    char name[SIZE];
    char organname[SIZE];
    char bloodtype[BLOODTYPESIZE];
    dateT dateAdded;
    timeT timeAdded;
    int received;
} organT;

int main(void) {
    int i, n, k, j;
    int c;
    int *ptr;

    char organ[SIZE];
    char bloodkind[BLOODTYPESIZE];

    organT patient[MAX];

    scanf("%d",&n);
    ptr = (int *)malloc(n * sizeof(*ptr));
    printf("Enter patient information\n");
    for(i=1; i<=n; i++){
        scanf("%s", patient[i].name[SIZE]);
        scanf("%s", patient[i].organname[SIZE]);
        scanf("%s", patient[i].bloodtype[BLOODTYPESIZE]);
        scanf("%d %d %d", patient[i].dateAdded);
        scanf("%d %d", patient[i].timeAdded);
        patient[i].received = 0;
}
scanf("%d", &k);
for(j=0; j<k; j++) {
    gets(organ);
    printf("Organ received: %s", organ);
    gets(bloodkind);
    printf("Organ has blood type: %s", bloodkind);
}
for (c=0; c<n; c++){
    if(patient[i].organname == organ){
        if(patient[i].bloodtype == bloodkind){
            if(patient[i].received == 0) {
                printf("Patient(s) Found!\n");
                printf("%s", patient[i].name[SIZE]);
                printf("Organ received: %s", organ);
                patient[i].received = 1;
            }
            if(patient[i].received == 1)
                printf("Patient already received organ\n");
        }
        else("Not correct blood type\n");
    }
    else("No match found\n");
}

return (EXIT_SUCCESS);
}

2条回答
劳资没心,怎么记你
2楼-- · 2019-09-14 11:40
  • First check n compare to MAX
  • here you access to bloodtype[BLOODTYPESIZE] but the last item in this tab is bloodtype[BLOODTYPESIZE-1]

        scanf("%s", &patient[i].bloodtype[BLOODTYPESIZE]);
    

The same problem is tru for other acces in the pararagraph.

查看更多
迷人小祖宗
3楼-- · 2019-09-14 11:47

Looks like you are not using the address correctly. For example, when you say

scanf("%s", &patient[i].name[SIZE]);

you are actually reading past the allocated space for patient[i].name. You should change the statement to

scanf("%s",patient[i].name);

and fix other statements similarly.

查看更多
登录 后发表回答