Hi, I've ran into a problem with pointers which I can't seem to get my head around.

Here's some code that illustrates my problem.

void Reallocate(char* Source)
{
	int NumberTest = 0;
	char* Buffer = new char[4];
	memcpy(Buffer, Source, 4);
	delete[] Source;
	Source = Buffer;
	memcpy(&NumberTest, Source, 4);//This puts the value 10 in NumberTest
}

int main()
{	
	int NumberOne = 10;
	int NumberTwo = 0;
	char* Buffer = new char[4];
	memcpy(Buffer, &NumberOne, 4);

	Reallocate(Buffer);
	memcpy(&NumberTwo, Buffer, 4); //This returns some garbage value.

//	delete[] Buffer;
	return 0;
}

This is what I think should happen.
1. On line 15 I allocate 4 bytes of memory.
2. On line 16 I copy the integer variable NumberOne into my Buffer.
3. On line 4 I allocate another 4 bytes of memory.
It's from this step that something isn't working as I think it does.
4. On line 5 I copy the content of the memory location pointed to by Source to the memory location pointed to by buffer.
5. On line 6 I call operator delete[] on the memory that Source points to.
6. On line 7 I assign the memory location pointed to by Buffer to Source.
7. On line 8 I perform a test to see if Source still holds the same value, it does.
This is where it gets weird.
8. When I return from the function and call memcpy on line 19 I get a garbage value.
9. If I try to call operator delete[] on Buffer my program crashes.

In my world Source points to the location in memory I allocated inside the function Reallocate after that function returns, and it should be ok to get the value from that memory location and then delete it when I'm done with it. But obviously that's not happening and I can't figure out why, any help is appreciated.

It makes absolutely sense that this doesn't make sense at first sight ;).

void Reallocate(char* Source)

Here, Source is a _copy_ of char* Buffer. So modifying what Source points to will leave Buffer completely untouched.

Only if you modify the thing-that-Source-points-to you will also modify the thing-that-Buffer-points-to .. because they point to the same thing.

So essentially you have 2 pointers pointing to the same thing, and you modify what one of those pointers points to.


Change realloc to take a char** as argument, and hand over &Buffer, then you can modify what Buffer points to.

commented: Thanks +1

Stupid me :) thanks for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.