簡體   English   中英

嘗試加載內核模塊時,如何解決C ++中的malloc()錯誤?

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

我在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失敗,則列出的代碼將失敗。 檢查讀取返回的字節數也是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM