1

I'm trying to check if a pointer is NULL in an array of pointer. Program crash when running, debbugger point to the if() condition but I don't know what it wrong.

In main.c

  unsigned int** memory = malloc(sizeof(unsigned int*)*MEMORY_SIZE);

    /* malloc failed */
    if (!memory)
    {

       return EXIT_FAILURE;
    }

    Process myProcess = { 1, 2, -1};

    /* TEST THAT WORKS */
    /* memory[0] = &(myProcess.m_id); */
    /* printf("%u", *memory[0]); */


    AllocFirstFit(&myProcess, memory);

In another .c file

void AllocFirstFit(Process* process, unsigned int** memory)
{
    unsigned int itr_mry;
    /* Declaration of various other local variable here*/

    /* browsing the memory */
    for(itr_mry = 0; itr_mry < MEMORY_SIZE; ++itr_mry)
    {
        /* if memory unit is null */
        /* debugger point this line. This condition is never true for some reason */ 
        if(memory[itr_mry] == NULL)
        {

2 Answers 2

3

You need to initialise the contents of the array memory to NULL yourself: the compiler will not do this for you on a malloc call. Currently the behaviour of your program is undefined since you're reading back an uninitialised pointer value.

The best thing to do is use calloc which will set pointers to the null pointer value.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah thank you, i didn't pay attention. I used calloc and the condition is working just find
2

In your code, while malloc()ing memory, you allocated some memory to the variable memory. You never initialized the contents of *memory or memory[i]. They may not be NULL, as you're expecting. They may very well contain garbage values.

So, basically, later,

 if(memory[itr_mry] == NULL)

is an attempt to use uninitialized memory which leads to undefined behavior.

Solution: You need to use calloc() to get a zero-initialized memory so that you can at least run the NULL check on *memory or memory[i].

1 Comment

Ah thank you, i didn't pay attention. I used calloc and the condition is working just find.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.