【问题标题】:Finding the memory allocated in program? [duplicate]查找程序中分配的内存? [复制]
【发布时间】:2012-11-22 22:17:38
【问题描述】:

可能重复:
How can I get the size of an array from a pointer in C?
How can I get the size of a memory block allocated using malloc()?

void func( int *p)
{
      // Add code to print MEMORY SIZE which is pointed by pointer p.
}
int main()
{
      int *p = (int *) malloc(10 * sizeof(int));
      func(p);
}

我们如何从 func() 中的内存指针 P 中找到 MEMORY SIZE ?

【问题讨论】:

  • malloc(10) 应该是 malloc(10 * sizeof(int))

标签: c memory-management malloc


【解决方案1】:

您不能在 C 中以可移植的方式执行此操作。它可能不会存储在任何地方; malloc() 可以保留比您请求的区域大得多的区域,并且不能保证存储有关您请求的大小的任何信息。

您要么需要使用标准大小,例如malloc(ARRAY_LEN * sizeof(int))malloc(sizeof mystruct),要么需要使用指针传递信息:

struct integers {
    size_t count;
    int *p;
};

void fun(integers ints) {
    // use ints.count to find out how many items we have
}

int main() {
    struct integers ints;
    ints.count = 10;
    ints.p = malloc(ints.count * sizeof(int));
    fun(ints);
}

【讨论】:

    【解决方案2】:

    没有内置逻辑来查找分配给指针的内存。 正如布赖恩在他的回答中提到的那样,您必须实现自己的方法。

    是的,您可以使用 linux 上的 valgrind 等工具找到内存泄漏。 在 solaris 上有一个库 libumem.so,它有一个名为 findleaks 的函数,它会告诉您在进程处于运行状态时泄漏了多少内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 2015-12-28
      • 2018-05-05
      相关资源
      最近更新 更多