Domanda

I'm trying to understand a c code, (SimpleScalar, bpred.c), there is the thing that confuses me a lot:

    int *shiftregs;
    shiftregs = calloc(1, sizeof(int));

    int l1index, l2index;
    l1index = 0; 
    l2index = shiftregs[l1index];

I delete some code that might not help. After the calloc call, *shiftregs becomes a pointer array? And what is the value of l2index? Thanks a lot!

È stato utile?

Soluzione

Since shiftregs is a pointer to an int, *shiftregs is an int.

Since calloc guarantees that the memory it allocates is set to 0, and you've allocated enough memory to refer to shiftregs[0], l2index will be 0 (assuming calloc didn't fail and return NULL).

Altri suggerimenti

The calloc() function is being used to allocate a dynamic array of zeroed integers that can be referenced via the pointer shiftregs.

The value in l2index is going to be zero unless the allocation failed (calloc() returned NULL). If the allocation failed, you invoke undefined behaviour; anything could happen, but your program will probably crash. Check the allocation so that it doesn't crash!

l2index is 0. calloc set memory to zero. Following is Linux Programmer's Manual:

calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

Check if the calloc() return NULL. If so, the "l2index = shiftregs[l1index];"will crash, for you try to get value from a NULL point(shiftregs). If not, as they said l2index will be 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top