Design a safe array getter for the stack-based array

If you are a C programmer, then you may know dealing with array of C is kinda picky. For example, your co-workers and you might have made a mistake such that trying to access out of index of an array.

If the memory violation error comes up in development cycle, you are lucky! That is not the worst case. But imagine, you made a service and launched on time. All of sudden, the service crashed and you have to SOLVE the problem before the next morning. Also you don’t have a debugger such as GDB and that error is came up in the unrelated part of source code. DAMNNN… that’s horrible…

This is for that case although it is not a perfect solution. I just wanna give you a little helpful hint. So let’s dig in!

What is the stack-based array?

The term, stack-based array, is not actually existed one. I just made it. In this article, the term, stack is a block of memory space where saved temporary data when your code get in/out a function. So, stack-based array means you make an array in a function and it is alive only in a block scope.

To improve the readability of our code, we make a bunch of useful macro functions.

Step 1. ARRAY_SIZE macro

ARRAY_SIZE takes an array and returns a number of array elements. That must not be used on uncountable array such as a pointer to an array.

#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))

Step 2. BOUNDARY_CHECK macro

#include <assert.h>
#define BOUNDARY_CHECK(array, idx) \
    assert(idx >= 0 && idx < ARRAY_SIZE(array))

We use assert for catching an error at runtime. Why assert? because assert is an expression! That’s so important! We will see sooner.

Step 3. get_array_elem macro

I will show you the code first, then explain how it works.

#define get_array_elem(_array, _idx) \
    ( BOUNDARY_CHECK(_array, _idx), _array[_idx] )

Only expressions could be placed between ( and ). Do you remember? I said assert is an expression! Also comma is a sequence point. That means compiler guarantees to execute BOUNDARY_CHECK first. The last part, the right side of the comma, returns its value. So the macro could be used as below:

int mynumber[] = { 1, 2, 3, 4, 5, 6, 7 };
int save = get_array_elem (mynumber, 1);

Go to gist for full code

Thank you for reading and take care 🙂

One thought on “Design a safe array getter for the stack-based array

  1. Pingback: [Leesoo Ahn] Design a safe array getter for the stack-based array - DEVBLOG - 개발자 메타블로그

Leave a comment