Skip to main content
GameDev.net gamedev.net
🔒 Locked

Wierd pointer freeing problem..

Started by Illumini Dec 22, 2002 at 12:14 AM 5 replies 150+ views
Original Post
Illumini
Illumini
Take // Client[socket].UserNum is a int. // declare a char pointer and reserve 4 bytes of RAM char *num = (char *)malloc(sizeof(int)); // convert the int into chars num = (char *)&(Client[socket].UserNum); // free the 4 bytes of RAM free(num); There is actually more to it than this but ive narrowed the problem down to here. Its the free command that generaes and Assertion error with Abort/Ignore/Retry. It says dbgheap.c generated an error in line 1011 when it was checking to see if it was a valid heap pointer. Now I just don''t understand how in the world that a little data can screw up the pointer... My only theory is that what im doing is highly illegal... However all the code associated with this worked fine untill i added the free. I mean the num came out with the right data I''m pretty sure.... If I can''t assign it to num this way how can I do it?
Sneftel
Sneftel
char *num = (char *)malloc(sizeof(int));
This line allocates memory on the heap.

num = (char *)&(Client[socket].UserNum);
This line throws away the memory you just allocated, and instead makes num point to an element in a Client object.

free(num);
This line frees that element, which was not allocated with malloc. That''s why you get the error.


Don''t listen to me. I''ve had too much coffee.
Sneftel
Sneftel
What exactly are you trying to do?


Don''t listen to me. I''ve had too much coffee.
Illumini
Illumini
ahh I see

It''s 1AM and ive been mesisng with this all day... starting to hurt my head I think...

I getwhat your saying now.

What I want to do is user the 4 bytes i allocated to store a int in char form so I can send it over Winsock.

So...

char *num = (char *)malloc(sizeof(int));

What goes here? I need to copy the Client[socket].UserNum into the 4 bytes I allocated..

free (num);

Sneftel
Sneftel
memcpy is what you want. Alternatively, just put (char *)&(Client[socket].UserNum) as the data argument to your send function, and avoid the extra copy.


Don''t listen to me. I''ve had too much coffee.
Illumini
Illumini
Yea thats how I do it most of the time..
but I got a wierd situation this time...

I need to make a char * with two ints and another char* so I kinda need them seperate form the send function. then I jsut send the whole char *.
Sneftel
Sneftel
You mean they need to be sent adjacently in the stream? Well, you could just send them one element at a time. Alternatively, you could make them the elements of a struct and send that.... make sure to turn off struct padding, tho.


Don''t listen to me. I''ve had too much coffee.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.