[英]C Programming on Xcode - EXC_BAD_ACCESS
我目前正在編碼一個C程序,以在文件中創建,查看和更新員工記錄。 我的程序沒有嚴重錯誤,一切順利進行,直到我輸入了員工ID,Xcode都會給出EXC_BAD_ACCESS錯誤。
我回到了我的代碼,這發生在應該將數據寫入文件的部分(請參閱注釋),但是我仍然不確定這里出了什么問題。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 300
struct emp
{
int id;
char *name;
}*emp1, *emp3;
void display();
void create();
void update();
FILE *fp, *fp1;
int count = 0;
void main(int argc, char **argv)
{
int i, n, ch;
printf("1] Create a Record\n");
printf("2] Display Records\n");
printf("3] Update Records\n");
printf("4] Exit");
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
fp = fopen(argv[1], "a");
create();
break;
case 2:
fp1 = fopen(argv[1],"rb");
display();
break;
case 3:
fp1 = fopen(argv[1], "r+");
update();
break;
case 4:
exit(0);
}
}
}
/* To create an employee record */
void create()
{
int i;
char *p;
emp1 = (struct emp *)malloc(sizeof(struct emp));
emp1->name = (char *)malloc((size)*(sizeof(char)));
printf("Enter name of employee : ");
scanf(" %[^\n]s", emp1->name);
printf("Enter emp id : ");
scanf(" %d", &emp1->id);
fwrite(&emp1->id, sizeof(emp1->id), 1, fp); //The error occurs here
fwrite(emp1->name, size, 1, fp);
count++; // count to number of entries of records
fclose(fp);
}
/* Display the records in the file */
void display()
{
emp3=(struct emp *)malloc(1*sizeof(struct emp));
emp3->name=(char *)malloc(size*sizeof(char));
int i = 1;
if (fp1 == NULL)
printf("\nFile not opened for reading");
while (i <= count)
{
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name, size, 1, fp1);
printf("\n%d %s",emp3->id,emp3->name);
i++;
}
fclose(fp1);
free(emp3->name);
free(emp3);
}
void update()
{
int id, flag = 0, i = 1;
char s[size];
if (fp1 == NULL)
{
printf("File cant be opened");
return;
}
printf("Enter employee id to update : ");
scanf("%d", &id);
emp3 = (struct emp *)malloc(1*sizeof(struct emp));
emp3->name=(char *)malloc(size*sizeof(char));
while(i<=count)
{
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name,size,1,fp1);
if (id == emp3->id)
{
printf("Enter new name of emplyee to update : ");
scanf(" %[^\n]s", s);
fseek(fp1, -204L, SEEK_CUR);
fwrite(&emp3->id, sizeof(emp3->id), 1, fp1);
fwrite(s, size, 1, fp1);
flag = 1;
break;
}
i++;
}
if (flag != 1)
{
printf("No employee record found");
flag = 0;
}
fclose(fp1);
free(emp3->name); /* to free allocated memory */
free(emp3);
}
您在評論中提到fp
為NULL。 這意味着您實際上沒有要寫入的打開文件。 較早的fopen
調用返回NULL表示錯誤。 崩潰的直接原因是fwrite
通過嘗試訪問應該指向的FILE
結構的字段來取消引用空指針。 間接的原因是您在使用fopen
之前沒有檢查它的返回值。
在每個fopen
調用之后,添加如下內容:
if (fp == NULL)
{
perror("Failed to open file");
exit(1);
}
當fopen
失敗時,它將返回NULL並設置全局變量errno
來指示出了什么問題。 perror
函數打印與errno
值相對應的描述性消息。
因為你的程序需要被賦予在命令行上的文件名(即argv[1]
確保Xcode中實際上是給它一個。啟動程序從IDE通常運行它沒有默認情況下任何命令行參數。訪問argv[1]
當argc
小於2時,將是另一個錯誤,並且可能會顯示為不是有效文件名的垃圾字符串,從而導致fopen
失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.