malloc()返回一个空指针

Mig*_*ell 0 c malloc

我正在尝试一个C编程分配,我需要迭代文档每行的每个索引,并在相应的数组ar中的每个字符索引处设置一个整数值:

//Jagged array ar containing pointers to each row
int* ar[line_count];
//The size of each row is the line width * the size of an int ptr
const int line_size = max_width * sizeof(int*);

//For each line
for (i = 0; i < line_count; i++)
{
    //If the first runthrough, copy the blank array 
    if (i == 0)
    {
        ar[i] = malloc(line_size);
        memcpy(ar[i], blank_ar, line_size);
    }
    //Otherwise, copy from the last row
    else
    {
        ar[i] = malloc(line_size);
        //This is set to a null pointer after several runthroughs
        memcpy(ar[i], ar[i - 1], line_size);
    }
    //Edit the current row ar[i]
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,经过大约9次迭代后,malloc开始返回一个空指针,导致memcpy(显然)不起作用.

这有什么原因吗?我没办法耗尽内存,因为我只分配了9次微小的数组.

Dav*_*nan 6

malloc它将在失败时返回空指针.可能发生这种情况的一些明显原因:

  • 你已经耗尽了堆内存.如果line_size非常大,这似乎是合理的.
  • 你已经破坏了堆.如果您正在运行的代码中存在错误,但是为了询问此问题而删除了该错误,则可能发生这种情况.

检查价值errno以找出有关故障的更多信息.

  • 使用`strerror()`来获取`errno`所代表的错误的文本表示.或者更简单的调用`perror()`将它打印到控制台.像这样:`perror("malloc failed");` (2认同)