c - read() return extra characters from file -


i trying read text file print.. while trying if give char buffer size returns character ..

#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h>  int main(){      int fd = open("text.txt",o_rdonly);      char cbuffer[100];     int =0;     if(fd>0){         puts("file open");         ssize_t len = read(fd,cbuffer,sizeof(cbuffer));         =printf("%s",&cbuffer);         printf("\n return data count  %d",a);     }      return 0;  } 

if instead of

ssize_t len = read(fd,cbuffer,sizeof(cbuffer)); 

to

ssize_t len = read(fd,cbuffer,10); 

returns 10 chars . can explain why happening?

this happens because, read() not null-terminate output. need null-terminate destination buffer before using string.

basically passing non-null terminated char array printf() argument %s creates undefined behavior there can out of bound memory access.

one way of achieving 0-initialize destination. way, considered null-terminated after valid values read , stored read(). like

  char cbuffer[100] = {0}; 

can help.

that said, change

 printf("%s",&cbuffer); 

to

printf("%s",cbuffer); 

as %s expects pointer null-terminated array of chars. when pass array name function, decays pointer first element, should ok.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -