c++ - Segmentation Fault on string conversion? -
i working on encryption project , making simple test takes file name terminal , runs encryption. have following encryption code following segmentation fault:
terminate called after throwing instance of 'std::logic_error' what(): basic_string::_m_construct null not valid<br><br> program received signal sigabrt, aborted. 0x00007ffff74ab428 in __gi_raise (sig=sig@entry=6) @ ../sysdeps/unix/sysv/linux/raise.c:54 54 ../sysdeps/unix/sysv/linux/raise.c: no such file or directory.
after running trace gdb have confirmed fault triggered after following loc:
string plain(reinterpret_cast(filecontents), filelength);
my main function below calls piece of code:
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string> #include <fstream> #include <limits> #include <sstream> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "rc4_enc.c" #include "rc4_skey.c" using namespace std; void foo(int); int main(int argc, char * argv[]){ if(argc!=2){ cout << "please enter filename want encrypt or decrypt\n"; exit(2); } int fd; fd = open(argv[1], o_rdonly); cout << "the file descriptor " << fd << endl; //close(fd);// can modify if it's closed? foo(fd); return 0; }
and function follows:
void foo(int fd) { int filelength = lseek(fd, 0, seek_end); unsigned char* filecontents; filecontents = (unsigned char*) calloc(filelength, sizeof(char)); pread(fd, filecontents, filelength, 0); string plain(reinterpret_cast<char*>(filecontents), filelength); // segfault happens here. why? rc4_key key; int length = plain.size(); unsigned char *buf = (unsigned char*)malloc(length+1); memset(buf, 0, length+1); ifstream pass; pass.open("pass.txt"); if(!pass.good()){ return; } else{ string password; getline(pass,password); rc4_set_key(&key, password.length(), (const unsigned char*)password.c_str()); } rc4(&key, length, (const unsigned char*)plain.c_str(), buf); string result((char*)buf, length); free(buf); const char *outputbuf = result.c_str(); pwrite(fd, outputbuf, result.length(), 0); ftruncate(fd, result.length()); }
i leave comment, not have enough reputation.
how large file? calloc failing , returning null? if it's not that, might wise check calloc's return value. or use new operator, try/catch.
Comments
Post a Comment