0
我一直在打开一个非常简单的读取文件的任务。使用perror,我发现报告的错误是“错误的地址”。这是什么意思,我该如何解决它?C:读取的地址不好
int freqCheck(char * fileName) {
/*Allocate buffer*/
struct stat fileStat;
stat(fileName, &fileStat);
int size = fileStat.st_size + 1;
void * buf = malloc(size);
memset(buf, 0, sizeof(buf));
if(buf = NULL) {
printf("An error has occurred while allocating memory\n");
return 0;
}/*End if*/
/*Read file*/
int fd = open(fileName, O_RDONLY);
if(fd < 0) {
perror("Open error");
return 0;
}/*End if*/
ssize_t num;
while((num = read(fd, buf, size - 1)) > 0) {
printf("num = %d\n", num);
}/*End while*/
if(num < 0) {
perror("Read error");
return 0;
} else if(num == 0) {
printf("Read worked!");
}/*End else if*/
}/*End freqCheck*/
与你没有关系的问题,但memset(buf,0,sizeof(buf))'没有做你认为的事情,也没有必要。 – 2013-03-22 17:20:42
谢谢你指出。它应该是大小。 – kubiej21 2013-03-22 17:23:29
与问题无关:但是当您为指针分配一些内存时,应该在调用malloc之后立即检查分配是否失败(即ptr == NULL)。您在malloc调用后立即拥有memset。所以,如果您的分配失败,程序会尝试写入NULL,导致写入无效! – 2013-03-22 17:24:07