0

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!

3
  • Have you seen union yet? Commented Oct 7, 2013 at 4:21
  • 2
    you are passing address of a pointer to memset. Try passing the pointer Commented Oct 7, 2013 at 4:21
  • 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. Commented Oct 7, 2013 at 4:34

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well now I feel really stupid. Removing the & fixed it. Thanks!
0

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)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.