c++ - 当我尝试加载内核模块时,如何修复 C++ 中的 malloc() 错误?

标签 c++ malloc

当我在 C++ 中执行此代码时,出现错误 malloc(): memory corruption。基本上,我打开一个内核文件并使用大小为 struct stat st 的 malloc。我想这是导致问题的原因。

代码加载了一个内核模块(I2C),它实际上正在加载。但我想我没有像应该使用的那样使用 malloc() 。谢谢。

#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#define init_module(mod, len, opts) syscall(__NR_init_module, mod, len, opts)
#define delete_module(name, flags) syscall(__NR_delete_module, name, flags)
class I2CKernelModule : public testing::Test {
public:
    I2CKernelModule() {
    }
};
TEST_F(I2CKernelModule, TestAddAndRemoveKernelModule) {
    char *params;
    int fd;
    size_t image_size;
    struct stat st;
    void *image;

    // command: sudo insmod /root/i2c-tests/i2c-stub.ko chip_addr=0x20
    params = "chip_addr=0x20";
    fd = open("/root/i2c-tests/i2c-stub.ko", O_RDONLY);
    fstat(fd, &st);
    image_size = st.st_size;
    image = malloc(image_size);
    read(fd, image, image_size);
    close(fd);
    if (init_module(image, image_size, params) != 0) {
        perror("init_module");
        GTEST_FAIL();
    }
    free(image);
    GTEST_SUCCESS_("Kernel module loaded.");

    /*
    // sudo rmmod i2c_stub
    if (delete_module("i2c_stub", O_NONBLOCK) != 0) {
        perror("delete_module");
        GTEST_FAIL();
    }
    GTEST_SUCCESS_("Kernel module unloaded.");
    */
}

最佳答案

检查所有函数的返回值是否有错误。如果文件未打开、stat 失败或 malloc 失败,您列出的代码将失败。检查读取返回的字节数也是一个好主意。

关于c++ - 当我尝试加载内核模块时,如何修复 C++ 中的 malloc() 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52973161/

相关文章:

c - free()使用malloc保留的数据

检查是否有东西被 malloced

c++ - std::vector 上的嵌套循环

c++ - 重载 [] 运算符并引用对象本身

c++ - 如何使用 C++ 获取 LAN 网络上 IP 摄像机的所有 MAC 地址和端口号?

c - 什么时候给char *分配内存

c - 指向 char 的类型指针的内存分配疑问

c - 在哪里 malloc 用户缓冲区?用户代码还是库代码?

c++ - 我试图在 C++03 中嵌套 boost 的 "map_list_of",但显然构造不明确?

c++ - 返回指向类成员的指针——我应该避免它吗?