我正在尝试一个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次微小的数组.
malloc它将在失败时返回空指针.可能发生这种情况的一些明显原因:
line_size非常大,这似乎是合理的.检查价值errno以找出有关故障的更多信息.