2017-04-14 14 views
0

私は暗号化プロジェクトに取り組んでいます。私は端末からファイル名をとり、暗号化を実行する簡単なテストを行っています。私は、次の暗号化コードを持っているが、私は、次のセグメンテーションフォールトを取得:文字列変換のセグメンテーションフォルト?

文字列平野(reinterpret_castは:私はこの障害には、次のLOC後にトリガされていることを確認しているgdbでトレースを実行した後

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. 

を(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ファイルを#includeしていますか? –

+1

プリアドの直後に 'filecontents [filelength-1] = '\ 0';を試してください。ちょうど試みのために。あなたの 'filecontents'が正しく終了していないと思います。それが機能する場合は、長さを1だけ修正する必要があります。 –

+0

@NeilButterworthこれらの.cファイルには、すでに統合したopensslの 'RC4_set_key()'と 'RC4()'関数を使うために必要なすべての依存関係が含まれています。 – Callat

答えて

1

私はコメントとしてこれを残すだろうが、十分ではありません。評判。

ファイルのサイズはどれくらいですか? callocが失敗しNULLを返す可能性がありますか? それがそうでないとしても、callocの戻り値をチェックすることは賢明かもしれません。または、try/catchでnew​​演算子を使用します。

+0

ファイルは短いですが、6バイトですが、ファイルシステムのプロジェクトに組み込む前に、テストするファイルの範囲があります。これは6バイトでフォールトアウトします。私はcallocの返品を調べる – Callat

+0

うん、それだよ!ウォークスルーありがとう。 – Callat