Segmentation fault trying to read until header is encountered in C -


i new c pardon simplicity of question. trying write function (as lib, must robust) reads 1 byte (edit: serial port) until header start byte encountered. if finds it, read in rest of header , payload , store in struct. start of code looks (some pseudocode included):

soh_read = 0; bytes_read = 0; bytes_left = 1;  do{     n = read(fd, buf + bytes_read, bytes_left);     if(n < 0){         if(errno != eagain && errno != ewouldblock && errno != eintr){             return -1;         }     }else{         bytes_read += n;         if(!soh_read){             if(buf[0] != soh){                 bytes_read = 0;                 continue;             }         }         soh_read = 1;         //read header ...         //read payload ...  }while(timeout not reached); 

i assumed reset bytes_read 0 if soh not encountered , try read in buf[0] position again, overwriting garbage read. seems case of buffer overflow , why getting segmentation fault? why not work though? if so, best way go this? wanted start @ buf[0] it'd easy keep track of each of message fields. trying learn experts here, thanks.

you've left out information crucial diagnosing problem code stands. single important thing (probably) whether soh might occur later in file you've allowed room in buf.

that said, however, think i'd things rather differently: since apparently don't need (or care about) data precedes soh anyway, why not read data 1 character, overwriting previous value @ each iteration, , save more 1 byte of data after encounter soh have use it.

do {      read(fd, buf, 1);     if (n<0 && errno != ewouldblock && /* ... */)        return -1; } while (buf[0] != soh , !timeout_reached);  // read header here 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -