1
#include <stdio.h>
#include <stdlib.h>

int main()
{ 
    int *ptr = NULL;
    ptr = (int*)malloc(2*sizeof(int*));//memory allocation dynamically
    return 0;
}// What is the error in this type of allocation
4

3 回答 3

2

我猜你想为 2 个 int 分配空间(不是 2 个指向 int 的指针):

int *ptr = malloc(2*sizeof(int));//memory allocation dynamically
于 2013-11-08T10:49:14.527 回答
1

如果您仔细阅读编译错误,您就会明白这一点。

int *ptr = NULL;
ptr = (int*)malloc(2*sizeof(int*)); //wrong

上面的代码是错误的。它应该是:

ptr = malloc(2*sizeof(*ptr));

无需转换的返回值mallocvoid *将被安全铸造。此外,sizeof(*ptr)如果需要修改 ptr 的数据类型,使用更容易维护。

此外,当不再需要动态分配的内存时释放它,否则您将发生内存泄漏。

free(ptr);
于 2013-11-08T10:50:16.930 回答
0

问题出在sizeof(int*))而且应该是sizeof(int))

动态分配需要你告诉它你想要分配的字节大小,因此在这个例子中你应该使用sizeof(int).

于 2013-11-08T10:48:26.517 回答