I get a segmentation fault checking for if
if(chunk->nodeBlock->nextBlock == NULL)
on line 40, inside of createChunk. It seg faults after it's second run through the for loop, I checked to see if it was going inside of the if statement the first time around and it does. I also checked to see that chunk->nodeBlock->nextBlock has an existing address after the code block inside the if statement is ran, meaning it should go to the else statement on the second run through. However it seg faults as it checks the if statement the second time.
#include "Render.h"
#include "Block.h"
struct Chunk
{
struct Render *r;
struct Block *nodeBlock;
};
//struct Block *NewBlock = NULL;
float posOffset = 1.0f;
int blockCount = 0;
struct Chunk *makeChunk(struct Render *r)
{
struct Chunk *chunk = NULL;
chunk = malloc(sizeof(struct Chunk));
chunk->r = r;
chunk->nodeBlock = makeBlock(r->model->worldPosition);
chunk->nodeBlock->nextBlock = NULL;
return chunk;
}
//TODO: Change this so it doesn't take in the model (source of the node block) instead, take in a currentBlock block pointer.
void updateModelMatrix(struct Chunk *chunk)
{
makeModelMatrix(chunk->r->model,0,0,0,0);
}
void createChunk(struct Chunk *chunk)
{
vec3 nodeCoordinate;
nodeCoordinate[0] = chunk->nodeBlock->pos[0];
nodeCoordinate[1] = chunk->nodeBlock->pos[1];
nodeCoordinate[2] = chunk->nodeBlock->pos[2];
for(int x = 0; x<16; x++)
{
if(chunk->nodeBlock->nextBlock == NULL)
{
//only has the node block
blockCount++;// should be one now
nodeCoordinate[0] += posOffset * blockCount;
chunk->nodeBlock->nextBlock = makeBlock(nodeCoordinate);
//chunk->no
}
else
{
//get to the newest block.
while(chunk->nodeBlock->nextBlock != NULL)
{
chunk->nodeBlock = chunk->nodeBlock->nextBlock;
}
//after loop, we have reached the newest block
blockCount++;
nodeCoordinate[0] += posOffset * blockCount;
chunk->nodeBlock->nextBlock = makeBlock(nodeCoordinate);
}
}
}
void printChunk(struct Chunk *chunk)
{
struct Block *temp;
temp = chunk->nodeBlock;
if(temp == NULL)
{
printf("No blocks.");// should never print
}
else
{
while(temp != NULL)
{
printf("BLOCK:\n");
printVec3(temp->pos);
temp = temp->nextBlock;
printf("\n");
}
}
}
Edit: here is Block.h in case this is causing the problem:
struct Block
{
vec3 pos;
struct Block *nextBlock;
};
struct Block *makeBlock(vec3 pos)
{
struct Block *block = malloc(sizeof(struct Block));
block->pos[0] = pos[0];
block->pos[1] = pos[1];
block->pos[2] = pos[2];
return block;
}