...

/

Detect NULL Pointer Exceptions Due to Code

Detect NULL Pointer Exceptions Due to Code

Learn how to identify exceptions, find problem threads, and CPU instructions.

We have previously discussed how NULL pointer errors can result in segmentation faults due to the data. Now, we’ll see how the same problem can arise due to the code itself. 

Application source code

We have created an application that tries to access a value pointed to the NULL pointer. We can see the source code below.

Press + to interact
// Build:
// gcc main.c -pthread -static -o App2C
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void procA()
{
sleep(2);
int *p = NULL;
*p = 1;
}
void procB()
{
sleep(1);
void (*pf)() = NULL;
pf();
}
#define THREAD_DECLARE(num,func) void bar_##num() \
{ \
func; \
} \
\
void foo_##num() \
{ \
bar_##num(); \
} \
\
void * thread_##num (void *arg) \
{ \
foo_##num(); \
\
return 0; \
}
THREAD_DECLARE(one,sleep(-1))
THREAD_DECLARE(two,procA())
THREAD_DECLARE(three,sleep(-1))
THREAD_DECLARE(four,procB())
THREAD_DECLARE(five,sleep(-1))
#define THREAD_CREATE(num) {pthread_t threadID_##num; pthread_create (&threadID_##num, NULL, thread_##num, NULL);}
int main(int argc, const char * argv[])
{
THREAD_CREATE(one)
THREAD_CREATE(two)
THREAD_CREATE(three)
THREAD_CREATE(four)
THREAD_CREATE(five)
sleep(3);
return 0;
}

As expected, we got a segmentation fault. We can take a look at the source code to see what exactly is causing the problem. We can see that in the procA function, we are trying to dereference a NULL pointer on line 16. In the procB function, we are declaring a NULL function pointer and then trying to dereference it on line 25 to call the target function. We have spotted two problems in our code; let’s see which one is causing the segmentation fault.

Loading the core file

We are already familiar with how to load our core files along ...

Access this course and 1400+ top-rated courses and projects.