写入失败:地址错误

/* Write and rewrite */ #include #include #include #include #include int main(int argc,char* argv[]){ int i = 0; int w_rw = 0; int fd = -1; int bw = -1; int nob = 0; char* file_name = "myfile"; char buff[30] = "Dummy File Testing"; w_rw = 1; // 1 - write , 2 - rewrite nob = 1000000; // No of bytes to write printf("\n File - Create,Open,Write \n"); for(i = 0; i < w_rw; i++){ printf("fd:%d line : %d\n",fd,__LINE__); if((fd = open(file_name,O_CREAT | O_RDWR))< 0){ perror("Open failed!"); return -1; } printf("fd:%d",fd); if((bw = write(fd,buff,nob)) < 0){ perror("Write failed!"); return -1; } printf("\n Bytes written : %d \n",bw); } return 0; } 

我收到写入错误,尝试写入1MB字节的数据时,地址失败。 为什么会这样 ?

您的buff数组应至少为nob字节长,以便写入调用成功…

根据write write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd因此你超出了字符串缓冲区。

如果你想用字符串try fwrite填充文件,你可以指定字符串长度和写缓冲区的总次数(nob / strlen(buff)?)。

  ssize_t write(int fd, const void *buf, size_t nbytes); 

write()系统调用将从buf读取nbytes字节并写入文件描述符fd引用的文件。

在你的程序中, bufnbytes相比很小,所以write()试图访问无效的地址位置,因此它给出了Bad Address错误。

你的bufbuff [30]改为buf [1000000]你可以解决你的问题。

错误地址错误表示您提供的地址位置无效

维基百科用关于写的示例程序给出了很好的解释 。