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

How do I fix this malloc() error in C++ when I am trying to load a kernel module?

本文关键字:malloc 错误 C++ 何修复 加载 内核模块      更新时间:2023-10-16

当我在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.");
*/
}

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