I have a Segmentation fault according to my debugger but I don't know why.
Here is the code involved. Did I miss something ?
typedef struct Process Process;
struct Process {
unsigned int m_id;
unsigned int m_size;
int m_startAddr;
};
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
Process** processList = calloc(MEMORY_SIZE, sizeof(Process*));
unsigned int itr;
unsigned int nb_process = 0;
int previous_process = -1;
for(itr = 0; itr < MEMORY_SIZE; ++itr)
{
if(memory[itr] != NULL)
{
previous_process = *memory[itr]; // works but risk of integer overflow
processList[nb_process]->m_id = *memory[itr]; // segfault
processList[nb_process]->m_size = 1;
processList[nb_process]->m_startAddr = itr;
nb_process++;
}
}
}
EDIT : I tried to make the following changes :
Process* processList = calloc(MEMORY_SIZE,sizeof(Process));
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
unsigned int nb_process = 0;
int previous_process = -1;
unsigned int itr;
Process temp;
for(itr = 0; itr < MEMORY_SIZE; ++itr)
{
/* if memory unit is not occupied */
if(memory[itr] != NULL)
{
/* if process is not known yet */
if(*memory[itr] != previous_process)
{
previous_process = *memory[itr];
printf("previous_process %u \n", previous_process);
temp.m_id = *memory[itr];
temp.m_size = 1;
temp.m_startAddr = itr;
processList[nb_process] = temp;
nb_process++;
}
/* if the process is already known */
else
{
printf("size %u \n", processList[nb_process].m_size);
processList[nb_process].m_size++;
}
}
}
The output of previous_process is correct. However, the output of size got a problem. First, it has always two values below what it should (14 instead of 16, 30 instead of 32; etc...) at the end of the for loop. Worse, the count start at 0, while it should start at 1, since i initialize temp.m_size with one before copying it into processList. So the copy doesn't work... Why ? Should i use memcpy ?
NULL? Of course, there's no requirement forNULLto be bitwise zero, so it's not even certain thatcalloc()will createNULL-pointers, but in practice that is probably what is happening.**?memory[itr] != NULLis obviously insufficient. You also need to check whetherprocessList[nb_process] != NULL.*memory[itr]is not initialised. Accessing an uninitialised variable leads to undefined behavior, of which segmentation fault is one case.