Trouble Using Memset

@ScruffR,

I have been doing some research on trying to construct these arrays and you seem to be most knowledgeable. It is my understanding that the array is seeded with the “0” as I have it, but it appears that the first time the array is accessed the result is a huge random number. Any chance you see something obvious I am doing wrong?

#define MAX_NODES 150
int state;
int* pressureArr;
long* timesArr; // stores millis of last receive time 
int* states; // stores current state of each node, 0=no data, 1=off, 2=on
// Previous pressure storage / sticky value toggle algorithm
void initPressureAndTimesStore(){
    pressureArr = new int[MAX_NODES];
    timesArr = new long[MAX_NODES];
    states = new int[MAX_NODES];

    memset(pressureArr, 0, sizeof(int) * MAX_NODES);
    memset(timesArr, 0, sizeof(long) * MAX_NODES);
    memset(states, 0, sizeof(int) * MAX_NODES);
}

Thank you very much.

Nope, arrays only get initialized with zeros when they are declared global. Then the compiler can create a "initialization-prolog" for all globals.

There are a few things :wink:
First, when using new you also need to explicitly call delete for all new instances when not needed anymore otherwise you create a memory leak.
Second, your function is not thread save and not even guarded against multiple calls. One call of the function may create its instances but a subsequent call will overwrite the global pointers and you won't be able to delete the previous instance.

And as a tip for maintainability of your code:
Instead of explicitly having to state the datatype you could use this

 memset(pressureArr, 0, sizeof(*pressureArr) * MAX_NODES);

This way you can alter the type without having to revisit the memset() line.

Given all the above, it may be easier to do this instead of all the extra work

#define MAX_NODES 150

int pressureArr[MAX_NODES];
long timesArr[MAX_NODES];  
int states[MAX_NODES]; 

This way you cannot run into a memory leak and your array will be initialised correctly.
If you need to reinitialise it you can just write memset(states, 0, sizeof(states));

However, if you wanted a dynamic size of your arrays, you may need to go with a function like yours but also need to consider my points above.

1 Like

@ScruffR thank you very much for your feedback and for sharing your best practices.

As for the large random number, the source ended up being a simple mistake of the arrays being half the size of a hash table that is being utilized. Once the size of both were the same, the random large number issue was resolved. Amazing how simple things cause big problems, but always an opportunity to learn!

Thank you again.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.