c - 写入失败 : Bad address

标签 c

/* Write and rewrite */
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

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 字节的数据时出现写入错误,错误地址失败。为什么会这样?

最佳答案

write 的人说write() 从缓冲区指向的 buf 向文件描述符 fd 引用的文件写入 count 个字节,因此您正在溢出字符串缓冲区。

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

关于c - 写入失败 : Bad address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21303529/

相关文章:

c++ - 在设计和构建嵌入式系统时考虑 Chaos Monkey

执行垃圾邮件时,C 函数/对象未返回一致的输出

c - X11 应用程序无法使用/双缓冲绘制

c - 将特定的8位分配给uint8_t

c - 驻留在一个内存地址的两个整数变量?

c - 快速解决死锁?

c++ - 如何在变量中设置浮点精度

C2000 设备的 C 计算

c - "UDP Client For the TIME Service"在转换之前是否需要检查读取数据的长度?

java - 将特定格式的多个输入作为 java 中的单个输入