const int BLOCK_SIZE = 512;
int *BLOCK_MEM = (int *)malloc(sizeof(int) * 512);
Here you define a named constant with value 512 but then use a literal 512
. If these are supposed to be the same thing, use the named constant. If they are supposed to be different, define a second named constant and add a comment explaining why two different values are needed.
In C, unlike C++, it is not recommended to cast a call to malloc
because it can suppress certain error messages. Also, it is recommended to use sizeof *p
, where p
is the pointer being assigned or initialized, instead of sizeof (type)
, because the former automatically adapts if the type of p
is later changed, whereas the latter requires that the type be changed in two places. (So it is less work to change the former and less likely a human will mistakenly miss the fact they need to make the change in multiple places.)
So that line would become int *BLOCK_MEM = malloc(sizeof *BLOCK_MEM * BLOCK_SIZE);
.
int *pBuffer = &buffer[BLOCK_SIZE];
This initializes pBuffer
to point to end of buffer
, specifically to a place one beyond the last element of pBuffer
. That is probably not what you want to do. To initialize pBuffer
to point to the start of buffer, you could use int *pBuffer = &buffer[0];
. However, you could also use int *pBuffer = buffer;
, because the array buffer
will automatically be converted to a pointer to its first element when used this way.
pBuffer = &BLOCK_MEM;
This does not make sense with the previous line. int *pBuffer = &buffer[BLOCK_SIZE];
initializes pBuffer
and then pBuffer = &BLOCK_MEM;
immediately changes it, so the initialization had no effect. You should simply initialize pBuffer
to the value you want it to have. And, if pBuffer
is going to point to the allocated memory, you do not need to define buffer
at all, unless you need it for some other purpose.
Additionally, the types are wrong in this assignment. BLOCK_MEM
is a pointer to int
, so &BLOCK_MEM
is a pointer to a pointer to an int
(type int **
). But pBuffer
is a pointer to an int
(type int *
). So the compiler issues a message that this assignment has a problem.
To set pBuffer
to point to where BLOCK_MEM
points, use pBuffer = BLOCK_MEM;
.