【问题标题】:memory allocation size upper bound 20MB in my dll我的 dll 中的内存分配大小上限 20MB
【发布时间】:2018-12-12 10:28:48
【问题描述】:

我在创建自己的 DLL(用于学术……)时遇到问题。

在 DLL 项目的头文件中(编译选项为“C”), 我声明了三个函数来导出

// in dll1 header

#pragma once

#ifdef MYDLL
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif


MYDLL_API int Mmalloc(int**, int);
MYDLL_API int Mfree(int**);
MYDLL_API int Arrsum(int*, int);

它们只是简单的功能。

在 DLL .C 中

 //in dll.c 

#include "dll1.h"
#include <stdlib.h>

int Mmalloc(int** mem, int n) // just memory Allocation
{
    *mem = (int*)malloc(sizeof(n)*sizeof(int));
    if (*mem) return 1; // if succeed return 1
    return 0;           // or return zero
};

int Mfree(int** mem) // just memory Free
{
    free(*mem);
    return 1;
}

int Arrsum(int* arr, int n) // just some operate
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    return sum;
}

使用“预处理定义”->“MYDLL”以及“运行时库”->“/MD” 我建造它。

然后我创建了另一个项目(编译选项“default (c++)”) 添加从 DLL 头添加头添加外部“C”

#pragma once

#ifdef MYDLL
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif


extern "C"
{
    MYDLL_API int Mmalloc(int**, int);
    MYDLL_API int Mfree(int**);
    MYDLL_API int Arrsum(int*, int);
}

我也做了 main.cpp

#include <stdio.h>
#include <stdlib.h>
#include "dll1.h"

#define SZ 1000

int main()
{
    int* arr=0;
    int cnt = 0;
    while (1)
    {
        int ret = Mmalloc(&arr, SZ);
        printf(ret ? "YES\n" : "NO\n");

        for (int i = 1; i <= SZ; i++)
        {
            arr[i - 1] = i;
            printf("%d\n", arr[i - 1]);
        }

        printf("%d\n", Arrsum(arr, SZ));

        printf("cnt : %d\n", ++cnt);
        Mfree(&arr);
    }
};

我将 *.dll、*.lib 文件放置在正确的文件夹中。 这对我来说似乎很有效,但我发现了巨大的错误。

我在 main.cpp 中使用了while(1) 语法。 所以我的程序应该尽可能长时间地工作,但它会在某些时候停止。

我不知道什么是真正的问题。

我在 .dll 项目和 main.cpp 项目中更改了堆保留大小

但我的主程序总是停止。

在调试模式下,它会停止

或更大的尺寸(SZ 10000~100000)我有访问冲突

请帮帮我。我什至无法想象真正的问题是什么。

dll 中有语法错误吗? (函数中的内存分配?) 要么 编译器问题? ,窗户?还是什么?...

【问题讨论】:

  • 为什么我写我的帖子标题用“20MB”字是它通常在 2000~8000 数组大小分配后停止。大约 5000 * 4BYTE = 20,000BYTE = 20MB。有歧义请见谅

标签: c++ c windows visual-studio dll


【解决方案1】:

Mmalloc 正在分配 4 或 8 个整数(取决于系统上 sizeof(n) 的值),而不是 n 整数。然后,您的程序会通过缓冲区溢出表现出未定义的行为。

【讨论】:

  • 非常感谢!! .我犯了一个多么愚蠢的错误......没有你的评论,我会花很多时间在这个问题上真的谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2012-03-05
  • 2023-03-03
  • 2018-11-15
  • 1970-01-01
相关资源
最近更新 更多