creating fread&fwrite like functions

Hello everyone!

I have this here:
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
		int write( void *in, int insize, int count )
		{
			if( !isbinary ) return size; 
			int adsize = insize * count;
			char *ad = new char[adsize];
			ad = (char *)in;
			char *p = new char[size + adsize];
			if(size) 
			{
				spstr::copy( p, size + adsize, data, size );
				delete data; 
			}
			data = p;
			spstr::copy( size, data, size + adsize, ad, adsize );
			size = size + adsize;
		}

		int read( void *out, int outsize, int count )
		{
			if( pos >= size ) return -1;
			char *d = new char[outsize*count];
			spstr::copy( pos, d, outsize*count, data, size );
			out = (void *)&d;
			pos += outsize*count;
			return pos;
		}

write works fine but read doesn't work at all.
What am i doing wrong here?
Thanks!


Edit:
Got it working.
All i had to do was
out[0] = d[0]
out[1] = d[1]
and so on ...

now the function is like this:
1
2
3
4
5
6
7
		int read( void *out, int outsize, int count )
		{
			if( pos >= size ) return -1;
			spstr::copy( pos, (char *)out, outsize*count, data, size );
			pos += outsize*count;
			return pos;
		}


Anyways... if you see something in my code what should i do differently then please let me know.
Thanks
Last edited on
Your original post leaks the memory allocated at line 5.

What is data at line 10 and why do you delete it at line 11? It's generally a bad design idea to have a function delete random bits of memory.
I think you haven't considered pass-by-value semantics. To work in the original way you intended, you need an etra level of indirection for out:

1
2
3
4
5
6
7
8
9
10
		int read( void **out, int outsize, int count )
		{
			if( pos >= size ) return -1;
			char *d = new char[outsize*count];
			spstr::copy( pos, d, outsize*count, data, size );
// It is suggestive that you need to garbage-collect out at this point
			*out = (void *)&d;
			pos += outsize*count;
			return pos;
		}


Topic archived. No new replies allowed.