0

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{
        ...
    }
}
8
  • 3
    because seqList isn't initialized. Also size is always 1. Commented Dec 8, 2016 at 5:01
  • sizeof(seqList[x]) makes no sense. It will always evaluate to pointer size, meaning that your size will always be 1. You will have to store and maintain the current size yourself. sizeof will not help you here. Commented Dec 8, 2016 at 5:03
  • Also, you don't need to split your code into malloc and realloc branches. If seqList[] is properly initialized to nulls initially, then realloc will work properly on it. realloc can be used to "reallocate" a null pointer, in which case it is equivalent to malloc. Commented Dec 8, 2016 at 5:05
  • 2
    @Que Trac: No. Only objects with static storage duration are initialized automatically. Your array is not. Commented Dec 8, 2016 at 5:06
  • 1
    1. you should not assign the return value of realloc to the pointer that was passed as argument, directly. If the new allocation fails you get NULL and the old memory is lost. 2. You define seqList as array of "pointers to int". But then you allocate sizeof(int*) which makes it to array of pointers to pointer to int. You should alloc with sizeof(int). Commented Dec 8, 2016 at 8:13

2 Answers 2

1

Thanks, BLUEPIXY and AnT. It seems that there isn't any other solution, but to initialize the array as mentioned here

for (i = 0; i < n; i++)
    seqList[i] = NULL;
Sign up to request clarification or add additional context in comments.

Comments

-1

You have to initialize it to 'NULL' to NULL check the array of pointers .

  int* seqList[n] = {NULL};

or

for ( i =0 ; i < n ; i++)
seqList[i] = NULL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.