Tag Archives: write failed bad address

C language write() function analysis: write failed bad address

When running the following test program on the ARM development board, “Write Failed Bad address” would appear probabilistic:

/* Write test */
#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 = "testfile";
 char buff[30] = "Testing";

 w_rw = 1;       // 1 - write , 2 - rewrite
 nob = 1024;  // No of bytes to write

 for(i = 0; i < w_rw; i++){
        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;
}

write() function man manual. The description of this function is as follows:

Function definition: ssize_t write (int fd, const void * buf, size_t count); 
Function Description: write() writes a count of bytes from the memory specified by buf to the file specified by fd.
Return Value: If write() succeeds, it returns the actual number of bytes written (len). When an error occurs, it returns -1, and the error code is stored in errno.

Here the byte written from the buf file fd file is determined by the count, not the actual allocated memory of the buf file. Thus, there is a case for accessing invalid addresses (Bad address</code b>) : if the value of count is greater than the actual allocated memory size of buf, the write() function may attempt to access invalid addresses beyond the actual memory space of buf.
The problem with the above test code is that buf is small, only 30 bytes, and write() is trying to write 1024 bytes, which will probabilistically access the invalid address. This problem can be solved by simply modifying the following code:

        if((bw = write(fd,buff,sizeof(buf))) < 0){
                perror("Write failed!");
                return -1;
        }