Migwell
Migwell

Reputation: 20107

malloc() returning a null pointer

I'm attempting a C programming assignment where I need to iterate through each index of each line of a document, and set an integer value at each character index in a corresponding array 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]
}

The only problem is, after some 9 iterations, malloc starts returning a null pointer that causes memcpy to (obviously) not work.

Is there any reason this is happening? There is no way I'm running out of memory as I only allocate these tiny arrays 9 times.

Upvotes: 0

Views: 12786

Answers (2)

angeek86
angeek86

Reputation: 108

Maybe you stack is too little, try to modify the default stack at compile/linking time in your IDE. If you are using GCC take a look into this Change stack size for a C++ application in Linux during compilation with GNU compiler

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612884

malloc will return the null pointer when it fails. Some obvious reasons why this could happen:

  • You have exhausted heap memory. That is plausible if line_size is very large.
  • You have corrupted the heap. That could happen if there are errors in the code that you are running, but have removed for the purpose of asking this question.

Inspect the value of errno to find out more information about the failure.

Upvotes: 8

Related Questions