PDA

View Full Version : Dynamic memory allocation troubles


blerp
11-02-2002, 02:00 PM
Hi,

Just wondered if anyone could point me in the right direction with this stuff - I'm having problems with using the 'free()' function to clear up memory after deleting elements in a linked list.

Taking the following code as an example (just standard C, by the way):


typedef struct node {
char data;
struct node *next;
} node;

node *node1;

int main(int argc, char *argv[]) {

node *temp;

// set up a small linked list with two elements
node1 = (node *)malloc(sizeof(node *));
node1->next = (node *)malloc(sizeof(node *));

node1->data = 'a';
node1->next->data = 'b';

// attempting to delete the first element in the list
temp = node1; // assign temporary pointer
node1 = node1->next; // move the list pointer on one place
free(temp); // fails here

return 0;
}


I suspect I just need to clear things up a bit more by nullifying various bits and pieces, but from just messing around trying that kind of thing, I've not had any luck.

Any help would be greatly appreciated, as I'm not sure what I'm missing here. The error Visual Studio .NET returns is "DAMAGE: after Normal block (#43) at 0x00324228".

Cheers

PrBacterio
11-02-2002, 02:42 PM
node1 = (node *)malloc(sizeof(node *));
node1->next = (node *)malloc(sizeof(node *));

There`s your problem right there. You want to allocate a node, not a node *.

blerp
11-02-2002, 03:09 PM
Aha - that did the trick. Was hoping it'd be something as simple as that.

Many, many thanks for the reply - I was slowly going insane trying different permutations of the code after that, without ever paying any attention to what had gone before.

Cheers,