lzma: whats the problem with my compress / decompress function?

hi,
i am writing a compression/decompression thing from memory for my app but the problem is it cant allocate memory.
when i debug it, it gives assertion failure error in operator new (maybe it has a problem with allocation and/or deallocation of memory)
now, here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
void compress(char *in, char **out, unsigned int insize, unsigned int &outsize)
{
outsize=insize+insize/4 + LZMA_PROPS_SIZE;
char* data=new char[outsize];
if(data==NULL)
{
*out=NULL;
outsize=0;
return ;
}
if(LzmaCompress((unsigned char*)(data+LZMA_PROPS_SIZE), &outsize, (unsigned char*)in, insize, (unsigned char*)data, (size_t*)LZMA_PROPS_SIZE, -1, -1, -1, -1, -1, -1, -1)==SZ_OK)
{
*out=new char[outsize+4];
if(*out==NULL)
{
delete[] data;
outsize=0;
return ;
}
outsize=outsize+LZMA_PROPS_SIZE;
memcpy(*out, &insize, 4);
memcpy(*out+4, data, outsize);
delete[] data;
}
else
{
delete[] data;
*out=NULL;
outsize=0;
return ;
}
}

void decompress(char *in, char **out, unsigned int insize, unsigned int &outsize)
{
memcpy(&outSize, in, 4);    
char* data=new char[outSize];
if(data==NULL)
{
*out=NULL;
outsize=0;
return ;
}
if(LzmaUncompress((unsigned char*)data, &outsize, (const unsigned char*)(in+4), (SizeT*)insize, (unsigned char*)data+4, LZMA_PROPS_SIZE)==SZ_OK)
{
*out=new char[outSize];
if(out==NULL)
{
delete[] data;
outSize=0;
return;
}
else
{
memcpy(*out, data, outSize);
delete[] data;
}
}
else
{
delete[] data;
*out=NULL;
outsize=0;
return;
}
}

what am i doing wrong here?
i'm writing the uncompressed size into memory in order not to allocate more memory than needed.
thanks
Why don't you use std::string. No need to worry memory management.
https://www.cprogramming.com/tutorial/string.html
if (LzmaCompress(..., (size_t*)LZMA_PROPS_SIZE, ...) == SZ_OK)
It's expecting the address of a variable. By casting, you've told the type system to shut up and not tell you about the error.

EDIT:
If new fails, you'll have an exception. So all that noisy code in the if clauses won't get run.

http://www.asawicki.info/news_1368_lzma_sdk_-_how_to_use.html
Last edited on
Registered users can post here. Sign in or register to post.