c++ - 字符串转换的段错误?

标签 c++ casting rc4-cipher

我正在从事一个加密项目,我正在做一个简单的测试,从终端获取一个文件名并运行我的加密。我有以下加密代码,但出现以下段错误:

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 (sig=sig@entry=6)
    at ../sysdeps/unix/sysv/linux/raise.c:54
54  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.

在使用 gdb 运行跟踪后,我确认此故障是在以下 loc 之后触发的:

string plain(reinterpret_cast(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());
    }

最佳答案

我会把它留作评论,但没有足够的声誉。

文件有多大? calloc 会失败并返回 NULL 吗? 即使不是那样,检查 calloc 的返回值也可能是明智的。或者使用带有 try/catch 的 new 运算符。

关于c++ - 字符串转换的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415204/

相关文章:

Java:类型转换问题

java - 为 Spring Boot 应用程序启用 RC4 密码套件

c++ - 使用 C++ 在 Qt5 中显示曲线

c++ - 主区域 : "master region may not be closely nested inside of work-sharing or explicit task region" 的 OpenMP for 循环

c - 将无符号字符转换为有符号数据类型时,为什么在汇编中使用 movzbl?

go - 如何使用加密/rc4

java - 使用 RC4 在 java 中加密字符串并在 VBScript 中解密

c++ - 将值从一个函数传递给另一个 C++

c++ - MPI C 逐行发送矩阵到所有进程子进程 (MPI_COMM_SPAWN)

C++:如何将数组中的 2 个字节转换为无符号短