I am building a project in C that basically consists in the implementation of a simplified database using a b+ tree structure. I used Xcode for coding the main file as well as 2 local libraries, and when I compile the code trough the IDE it runs perfectly.
However if I build the code using a local Makefile that I wrote myself I get a segmentation fault in a random function in the code and that it shouldn't even be reached with the arguments I gave as input.
Here it is my Makefile
CC = gcc
CFLAGS = -g -O0
all: main.exe
main.exe: main.o b_tree.o queue.o
$(CC) $(CFLAGS) main.o b_tree.o queue.o -o main.exe
main.o: main.c b_tree.h queue.h
$(CC) $(CFLAGS) -c main.c
b_tree.o: b_tree.h b_tree.c
$(CC) $(CFLAGS) -c b_tree.c
queue.o: queue.h queue.c
$(CC) $(CFLAGS) -c queue.c
clean:
rm *.o main.exe
When I run using the following input arguments: ./main.exe ./my_answers/test_myanswer.txt ./testes_toy/test.txt 4 3
(output file name, input file name, tree order and size of the register to be stored in the tree), I get a segmentation fault.
I don't know it it would help but if I comment the function that sorts the children nodes it works:
void sortNodesChildren(Node *node){
if (node->numChildren == 0) {
return;
}
// Get all children nodes
Node *childrenNodes = realloc(NULL, sizeof(node)*node->numChildren);
for (int k = 0; k < node->numChildren; ++k) {
Node n = getNode(node->childNodes[k]);
childrenNodes[k] = n;
}
// Sort children nodes
for(int i = 0;i<node->numChildren;i++){
for (int j = i+1; j<node->numChildren; j++) {
Node aux; long auxId;
if (childrenNodes[i].registerKeys[0] > childrenNodes[j].registerKeys[0]) {
aux = childrenNodes[i];
auxId = node->childNodes[i];
childrenNodes[i] = childrenNodes[j];
node->childNodes[i] = node->childNodes[j];
childrenNodes[j] = aux;
node->childNodes[j] = auxId;
}
}
}
free(childrenNodes);
}
I feel like it may be something to do with the realloc
function, but I have no idea what or why it works when run trough Xcode. Maybe my Makefile may be missing something.