PDA

View Full Version : memset char * char[]



youfulan2015
3rd August 2015, 10:25
ULONG ncnt=10;

unsigned char * pBuffer=NULL;
pBuffer=(unsigned char * )malloc(ncnt);

// unsigned char pBuffer[ncnt];

memset(pBuffer,0,ncnt);
this works well.
but however when it comes blow I come into a C++ runtime error
ULONG ncnt=10;

//unsigned char * pBuffer=NULL;
// pBuffer=(unsigned char * )malloc(ncnt);

unsigned char pBuffer[ncnt];

memset(pBuffer,0,ncnt);
why?

yeye_olive
3rd August 2015, 14:35
The few lines of code you provided are correct, but it is likely that the context in which they are executed cause the error. The difference between

unsigned char * pBuffer = (unsigned char *)malloc(ncnt);
and

unsigned char pBuffer[ncnt];
is that in the first case, the array is allocated on the heap (and you must deallocate it yourself with free()), while in the second case it is allocated on the stack and automatically deallocated at the end of its scope. Your program probably accesses pBuffer outside its scope, after it has been deallocated, which causes an error at some point.

jefftee
4th August 2015, 06:37
When you switch from malloc/free to allocating the buffer on the stack, did you also comment the code that does free(pBuffer)? You can't free something allocated on the stack.