c++ - Custom read producing garbage -
i'm implementing own read function reads content file buffer. reads information in file when print out information has garbage null bytes '\00\' attached output. output read "hi\00\00\00th\00\00\00er\00e" when reading "hi there" have no idea causing , appreciated. i'm not sure if it's important or not '\00\' appear after 2 chars every time.
bool fileread(int ptrbuffer, int buffersize, int fid) { if (buffersize == 0) { debug('p', "cannot read 0 bytes.\n"); machine->writeregister(2, -2); return false; } char *buffer = (char *)malloc(sizeof(char *) * (buffersize +1)); debug('p', "attempting read %d bytes file %d\n", buffersize, fid); // read bytes file. openfile* file = openfiletable[fid - fid_offset]; if (file == null) { debug('p', "file not exist!\n"); machine->writeregister(2, -4); return false; } file->read(buffer, buffersize + 1); int len = strlen(buffer); debug('p', "read string %s len %d\n", buffer, len); buffer[len] = '\0'; strcpy(&machine->mainmemory[ptrbuffer], buffer); machine->writeregister(2, len-1); return true; }
you're not null-terminating bytes read, , you're ignoring how many bytes read:
file->read(buffer, buffersize + 1);
should be:
int nr = file->read(buffer, buffersize + 1); if(nr > 0) { buffer[min(nr, buffersize)] = '\0';
Comments
Post a Comment