Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete char* for byte conversion

Tags:

c++

c

I tried to read a binary file using different length byte every time I read the file. After I got the value, I try to convert the bytes to char*.

I created a simple code as follows:

//This code is compiled in Visual Studio 2010
typedef unsigned char BYTE;

BYTE *s;
s = new BYTE[3]; // I read 2 bytes from the file, I add +1 to reserve NULL
s[0]= 'a'; s[1]='b';s[2]=NULL;  //just an example I get 2 bytes from file

char* b;
b = new char(sizeof(s));
strcpy(b,(char*)s);
s[0]='x';
cout << s <<"--"<< b<< "--"<< endl;
delete[] s;
delete[]  b;
cin.get();
return 0;`

However, the code generates error "Heap Corruption Detected". When I removed the line, delete[] b; the program runs well. But I am not sure the next time if the problem may arise. Will somebody explain about it, please? Will it cause memory leak if I remove delete[] b;? Any suggestions to improve my code?

like image 803
user1917485 Avatar asked Dec 26 '22 12:12

user1917485


1 Answers

This:

b = new char(sizeof(s));

Should be:

b = new char[sizeof(s)];

Otherwise you are not creating an array, you are just just creating a pointer to a char that has the character code of sizeof(a).

And therefore delete[] b is causing it to crash because you are trying to delete an array where there is no array.

Also another problem, sizeof(s) is not going to give you what you want. s is a dynamically allocated array so calling sizeof(s) is not going to give you the sum of the sizes of chars in s. sizeof(s) will return the size of the pointer to s.

like image 109
David Saxon Avatar answered Jan 04 '23 23:01

David Saxon