Stefatronik
Stefatronik

Reputation: 332

c function: re-initialize a static array or declare new every call?

I wonder what is the best way if I want to use an zero-initialized array of n unsigned char elements within a function. n is approx. 600.

a) Newly declare the array at every function call:

unsigned char buffer[n] = {0};

b) Declare as static but memset every function call:

static unsigned char buffer[n] = {0};
memset (buffer, 0, n);

I would expect that memset and initializing in (a) would cost the same. But for (a) I need to allocate memory every funktion call and free it when I leave the function. This would not happen in (b) because the array is declared to be static. Am I right?

Upvotes: 0

Views: 755

Answers (1)

Lundin
Lundin

Reputation: 213513

Keeping it static means that it get zero-initialized at start-up, which does you no good here since you set it to zero in run-time anyway. If the system-specific static initialization is carried out in run-time, this would mean that you get a slower program start-up.

Also, static variables are not thread-safe, which may or may not be an issue.

What takes time in the stack allocation case, is not the allocation, but rather the zero-out. So if you are concerned about performance, the best solution is to not zero-initialize it at all, but instead ensure that the algorithm writes to each and every byte of the array. I don't know the algorithm here, but "I must have a local array of all zeroes with the size 600" is a strange requirement.

Upvotes: 1

Related Questions