Memory questions and functions-Collection of common programming errors

First, I will let you write your own code that is the best way to learn. But, I will answer the theory behind these questions…

1) when raising the number 2 to the nth power, is the same as multiplying 2 by itself n times. But multiplying by 2 is same as doubling a number, and computers store their numbers in base 2. For example, the binary value for 6 == 0b00110 but when all of the bits are shifted to the left by 1, then 12 == 0b01100, which is same as 6*2. So, for example, 16 == 4^2 = 4*4 = 4*(2*2)or in binary 16 == 0b010000 == 0b001000*2 = (0b00100)*2*2.

2) when a variable is declared outside of all routines it is in “global” storage, also probably called “Data”. When a variable is declared within a routine it is an “automatic” variable (meaning that it is automatically) and is allocated on the stack. When a variable is explicitly allocated, using malloc as one example, then it is allocated on the heap.

In C, pointers have two data components or storage elements. First, is the pointer itself which typically uses only 4 bytes. Then the data which is whatever length was allocated for the data. To say anything more will repeat information provided by other answers!

It is a good programming practice to free all storage that has been allocated on the heap. Although, the system should deallocate that storage when main exits, this is NOT always guaranteed especially on small or embedded systems. Thus, the code example should end as:

    free(c);
    return 0;