当我尝试编写打印文件中代码的代码时,收到一条错误消息“发生异常。EXC_BAD_ACCESS(代码=1,地址=0x68)”。
我用谷歌搜索过,但没有找到解决方案。
我需要有人的帮助。
谢谢
我认为这是因为内存分配的原因,所以我尝试使用malloc
和普通数组。然而,它们都不起作用。
这是代码。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fp;
fp = fopen("pO5.c", "rb");
// char buf[100];
char* buf;
while (1) {
buf = (char*)malloc(sizeof(buf) * 1000);
int n = fread(buf, 1, 100, fp);
if (n == 0) {
break;
}
fwrite(buf, 1, n, stdout);
}
fclose(fp);
return 0;
}
此代码预计会打印代码本身。
最佳答案
这里有一些观察。首先,这里
fp = fopen("pO5.c", "rb");
应始终检查 fopen()
的返回类型,以了解对 fopen()
的调用是成功还是失败。如果 fopen()
失败并且您正在 fp
上进一步操作,则可能会导致问题。需要适当的错误处理,例如
fp = fopen("pO5.c", "rb");
if(fp == NULL) {
fprintf(stderr, "Can't open %s: %s\n", "pO5.c", strerror(errno)); /* include header for errno */
exit(EXIT_FAILURE);
}
其次,这里
buf = (char*)malloc(sizeof(buf) * 1000);
int n = fread(buf, 1, 100, fp);
不要使用像 100
或 1000
这样的魔数(Magic Number),建议使用宏来实现此目的。
此外,sizeof(buf)
是指针的大小,但您希望它是 sizeof(*buf)
。
类型转换 malloc()
结果是 not required这里。例如
buf = malloc(sizeof(*buf) * BUF_MAX_SIZE); /* define BUF_MAX_SIZE */
还要检查 malloc()
的返回值,例如
buf = malloc(sizeof(*buf) * BUF_MAX_SIZE); /* define BUF_MAX_SIZE */
if(buf == NULL) {
/* @TODO error handling if malloc failed */
}
下面的代码块有缺陷
while (1) {
buf = (char*)malloc(sizeof(buf) * 1000);
int n = fread(buf, 1, 100, fp);
if (n == 0) {
break;
}
fwrite(buf, 1, n, stdout);
}
主要是因为一个原因
- 您没有释放每个 malloc 的内存吗? 每次使用新的动态地址重新分配
buf
且没有对象或指针时,内存泄漏 指向先前分配的内存。
上述问题的一个解决方案可以是这个
buf = malloc(sizeof(*buf) * BUF_MAX_SIZE); /* calling malloc() n times costs more, it can be avoided by allocating memory before while(1) block */
if(buf == NULL) {
/* @TODO error handling of malloc */
}
int n = 0; /* declare here */
while (1) {
n = fread(buf, 1, BUF_MAX_SIZE, fp); /* reading BUF_MAX_SIZE bytes every time from file & storing into buf */
if (n == 0) {
break;
}
fwrite(buf, 1, n, stdout);/* put buf to stdout */
/* zero'd the BUF_MAX_SIZE bytes of buf, can use memset() here */
}
free(buf); /* free here */
关于c - 我有一个关于打印的问题。 "EXC_BAD_ACCESS",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57238767/