C: Memory state during array declaration

I recently introduced a small assignment program that had the following two functions and the main method inside it:

/** * Counts the number of bits it * takes to represent an integer a */ int num_bits(int a) { int bitCount = 0; while(a > 0) { bitCount++; a = a >> 1; //shift to the right 1 bit } return bitCount; } /** * Converts an integer into binary representation * stored in an array */ void int2bin_array(int a, int *b) { //stopping point in search for bits int upper_bound = num_bits(a); int i; for(i = 0; i < upper_bound; i++) { *(b+i) = (a >> i) & 1; //store the ith bit in b[i] } } int main() { int numBits = num_bits(exponent); int arr[numBits]; //<- QUESTION IS ABOUT THIS LINE int2bin_array(exponent, arr); //do some operations on array arr } 

When my teacher returned the program, he wrote a comment about the line noted above, and said that since the value of numBits not known until runtime, initializing an array of size numBits is a dangerous operation because the compiler does not know how much memory is allocated to arr .

I was wondering if anyone could:

1) Make sure this is a dangerous operation

2) Explain what happens in memory when I initialize such an array as the compiler knows which memory to allocate? Is there any way to determine how much memory has been allocated?

Any inputs would be appreciated.

+4
source share
2 answers

This is a variable length array of C99. It is allocated at runtime (and not by the compiler) on the stack and is basically equivalent

  char *arr = alloca(num_bits); 

In this case, since you can know the upper bound of the function, and it is relatively small, you are better off with

  char arr[sizeof(int)*CHAR_BIT]; 

This array has the size known at compile time, will always match everything you need, and works on platforms without C99 support.

+2
source

This should be good, it just goes on the stack.
The only danger is blowing the stack.

malloc will be the usual way, then you know if you have enough memory or not, and you can make informed decisions about what to do next. But in many cases, it’s quite normal to assume that you can push not too large objects onto the stack.

But, strictly speaking, if you do not have enough space, this will go bad.

+2
source

Source: https://habr.com/ru/post/1397935/


All Articles