[英]How do I fix this malloc() error in C++ when I am trying to load a kernel module?
I am getting the error malloc(): memory corruption
when I execute this code in C++. 我在C ++中执行此代码时遇到错误malloc(): memory corruption
。 Basically, I open a kernel file and I use malloc with the size of struct stat st
. 基本上,我打开一个内核文件,并使用大小为struct stat st
malloc。 I guess this is causing the problem. 我猜这是造成问题的原因。
The code loads a kernel module (I2C) and it is actually loading. 该代码加载了内核模块(I2C),并且实际上正在加载。 but I guess I am not using the malloc()
as should be used. 但我想我没有使用应使用的malloc()
。 Thanks. 谢谢。
#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.");
*/
}
Check the return values of all functions for errors. 检查所有函数的返回值是否有错误。 The code you have listed would fail if the file doesn't open, the stat fails or the malloc fails. 如果文件未打开,统计信息失败或malloc失败,则列出的代码将失败。 It is also a good idea to check the number of bytes returned by read. 检查读取返回的字节数也是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.