malloc()返回一个空指针

时间:2013-04-24 07:51:11

标签: 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]
}

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

这是否有任何原因发生?我没办法耗尽内存,因为我只分配了9次微小的数组。

2 个答案:

答案 0 :(得分:6)

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

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

检查errno的值以找出有关失败的更多信息。

答案 1 :(得分:1)

也许堆栈太少,尝试在IDE中的编译/链接时修改默认堆栈。如果您正在使用GCC,请查看此Change stack size for a C++ application in Linux during compilation with GNU compiler