我正在尝试(动态地)创建一个数组并用随机数填充它。
我在 Linux 上。程序编译没有错误。这是 C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void create_array(int **, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);
int main()
{
int *A = NULL;
int size = 7;
int low = 10;
int high = 1000;
create_array(&A, size);
populate_array(A, size, low, high);
display_array(A, size);
return 0;
}
void create_array(int **X, int size)
{
*X = (int *)(malloc(size));
}
void populate_array(int *X, int size, int low, int high)
{
srand(time(0));
for (int i = 0; i < size; ++i)
{
*(X + i) = low + rand() % (high + 1 - low);
}
}
void display_array(int *X, int size)
{
for (int i = 0; i < size; ++i)
{
if (i % 10 == 0)
printf("\n");
printf("%d\t", *(X + i));
}
printf("\n");
}
但是,当我运行它时,出现以下错误:
malloc.c:2394: sysmalloc: 断言`(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' 失败。
中止(核心转储)
此错误仅在 size = 7
时产生。对于较低的值,一切都很好。但是对于更高的值,那就是另一回事了! size = 20
的输出:
455 526 335 719 907 695 1041 0 154481972 154546741
154481459 154743095 154482992 875836721 960049720 926419250 909326389 154219063 808465977 842479924
相比之下,C++ 中的相同程序(几乎)给出了预期的输出。这是代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void create_array(int *&, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);
int main()
{
int *A;
int size = 100;
int low = 10;
int high = 1000;
create_array(A, size);
populate_array(A, size, low, high);
display_array(A, size);
return 0;
}
void create_array(int *&X, int size)
{
X = new int[size];
}
void populate_array(int *X, int size, int low, int high)
{
srand(time(0));
for (int i = 0; i < size; ++i)
{
X[i] = low + rand() % (high + 1 - low);
}
}
void display_array(int *X, int size)
{
for (int i = 0; i < size; ++i)
{
if (i % 10 == 0)
cout << endl;
cout << X[i] << "\t";
}
cout << endl;
}
我做错了什么?
最佳答案
*X = (int *)(malloc(size));
您正在分配 size
字节数,也许您想要的是
*X = malloc(sizeof(int)*size);
Note: malloc takes number of bytes to be allocated as argument. Also for for
c
implementation you might want to read Why not to cast malloc return.
关于c - c 中的动态内存分配会引发特定大小的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54404906/