I have a fixed size array of integer pointers where I want to allocate from heap only if it is needed, but I can't seem to be able to get the following NULL check to work. malloc never get called first.
int* seqList[n];
for (int i = 0; i < q; i++) {
int type, x, y;
scanf("%d", &type);
scanf("%d", &x);
scanf("%d", &y);
if (type == 1) {
if (seqList[x] != NULL) {
int size = sizeof(seqList[x])/sizeof(int*);
seqList[x] = realloc(seqList[x], (size + 1)*sizeof(int*));
seqList[x][size] = y;
}
else {
seqList[x] = malloc(sizeof(int*));
}
}
else{
...
}
}
seqListisn't initialized. Alsosizeis always 1.sizeof(seqList[x])makes no sense. It will always evaluate to pointer size, meaning that yoursizewill always be 1. You will have to store and maintain the current size yourself.sizeofwill not help you here.mallocandreallocbranches. IfseqList[]is properly initialized to nulls initially, thenreallocwill work properly on it.realloccan be used to "reallocate" a null pointer, in which case it is equivalent tomalloc.reallocto the pointer that was passed as argument, directly. If the new allocation fails you getNULLand the old memory is lost. 2. You defineseqListas array of "pointers to int". But then you allocatesizeof(int*)which makes it to array of pointers to pointer to int. You should alloc withsizeof(int).