2017-04-14 31 views
0

我正在開發一個加密項目,我正在做一個簡單的測試,它從終端獲取一個文件名並運行我的加密。我有以下的加密代碼,但我得到以下分段錯誤:字符串轉換中的分段錯誤?

串平原(reinterpret_cast的:

terminate called after throwing an instance of 'std::logic_error' 
    what(): basic_string::_M_construct null not valid<br><br> 
Program received signal SIGABRT, Aborted. 
0x00007ffff74ab428 in __GI_raise ([email protected]=6) 
    at ../sysdeps/unix/sysv/linux/raise.c:54 
54 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory. 

運行使用gdb一絲我已經證實,這種故障是以下LOC後觸發後(fileContents),fileLength);下面

我的主函數調用這一段代碼:

#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 the filename that you want to encrypt or decrypt\n"; 
     exit(2); 
    } 
    int fd; 
    fd = open(argv[1], O_RDONLY); 
    cout << "The file descriptor is " << fd << endl; 
    //close(fd);// Can I modify it if it's closed? 
    foo(fd); 

    return 0; 
} 

而且功能如下:

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. But 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()); 
    } 
+1

你爲什麼#包括.c文件? –

+1

嘗試'filecontents [filelength-1] ='\ 0';'在pread之後;只是一個嘗試;我想你的'filecontents'沒有正確終止。如果它有效,你還必須修正長度爲1。 –

+0

@NeilButterworth那些.c文件包含所有必需的依賴關係使用'RC4_set_key()'&'RC4()'從OpenSSL的,我已經集成功能。 – Callat

回答

1

我將離開這個作爲一個評論,但沒有足夠的聲譽。

多大的文件? Calloc會失敗並返回NULL? 即使不是這樣,檢查calloc的返回值可能是明智的。或者用try/catch來使用新的操作符。

+0

該文件很短,6字節,但我有一個文件的範圍來測試它之前,我將它集成到我的文件系統項目。這在6個字節上出錯。我會研究calloc的回報 – Callat

+0

是的,就是這樣!感謝演練。 – Callat