0
votes

I'm trying to allocate some memory as unsigned char* however when I do the pointer doesn't seem to have been initialized!

    unsigned char* split = (unsigned char*) malloc ((sizeof(unsigned char)*sizeof(unsigned int)));
    memset(&split,0,sizeof(int));
    if(split==NULL) {
       std::cout<<"Unable to allocate memory!\n";
       system("pause");
       return 1;
    }

However every single time I run I get the error message. It seems to happen no matter what data type I use as well!

2
Have you seen union yet? - Ignacio Vazquez-Abrams
you are passing address of a pointer to memset. Try passing the pointer - Aman Deep Gautam
You'd be better off testing split == NULL before messing around with it, whether correct or incorrectly as you are doing here. If you use calloc() you can get rid of the memset() altogether. - user207421

2 Answers

4
votes

Your memset call doesn't write to the buffer you've just allocated, the one pointed to by split. It writes to the area of memory where split variable itself stored - as pointed to by &split. Whereupon split becomes NULL.

0
votes

When you are calling memset(), you are zeroing the memory occupied by the split variable itself, not the memory that split points to (the memory that malloc() allocated). You need to remove the & operator:

unsigned char* split = (unsigned char*) malloc (sizeof(int));
if(split==NULL) {
   std::cout<<"Unable to allocate memory!\n";
   system("pause");
   return 1;
}
memset(split,0,sizeof(int));