I am having problems with an array which i want to re-use in my program. I need to change the size dynamically and clear it. But unfortunately the resizing does not work.
uint8_t * readBuffer; // Create array pointer
readBuffer = (uint8_t *) malloc(4); // Mem. alloc. 4bytes
memset(readBuffer, 0, sizeof(readBuffer); // Reset array
// Do stuff
free(readBuffer) // Release mem. block
....
readBuffer = (uint8_t *) malloc(1) // Mem. alloc. 1byte
memset(readBuffer, 0, sizeof(readBuffer); // Reset array
// Do stuff
free(readBuffer) // Release mem. block
At the the resizing step the length of my array is still the former (4).
Am i using free all wrong?
Further more is there much more efficient alternatives to memset for clearing?
Thanks in advance.
Size of a pointer (e.g.
readBuffer) is always same (here 4 bytes) for any data type. You need to rather store the size given inside the malloc into a temporary and then usememset():Moreover argument to
malloc()is in bytes, somalloc(1)means ideally 1 byte. If you are using C++ then usenew:Edit:
In C++,
std::vectorprovides this facility with much ease:Here you are allocating ‘N’ elements for
readBufferand initializing them to0.Whenever you want to add elements, you can use
push_back()method. For bigger chunks you may also exploreresize()orreserve()methods.