Problems with pointers and malloc()
Hi there,
I'm having problems with dynamic memory management and pointers. I guess the problem has got something to do with the fact, that I don't want to malloc() (and check the result with if...) many times in my program. So I decided to create a function that gets the pointer, to where it is supposed to malloc() memory and write data.
Btw, the program is supposed to do a depth first search on an 8-puzzle problem...
Here the most important parts of the code, with the two problematic parts marked. Sorry for posting so much code, but I couldn't shorten it even more without losing the context.
Code:
#include <stdio.h>
#include <stdlib.h>
int depth_max;
typedef struct node {
int value[3][3];
struct node *next;
struct node *prev;
} node;
void printNode(node *k) { ... }
int equal(int value1[3][3], int value2[3][3]) { ... }
/**
* Appends node2 after node1 (doubly-linked list)
*/
void appendToList(node *k1, node *k2) {
printf("appendToList() entering ...\n");
k1->next = k2;
k2->prev = k1;
return;
}
/**
* Creates a node which is similar to node k. Allocates memory for node "new"
*/
void newSuccessor(node *k, node *new, int x1, int y1, int x2, int y2) {
node *tempNode;
if ((tempNode = (node *)malloc(sizeof(node))) == 0) {
printf("No more memory left!\n");
return;
}
*new = *tempNode; // !!! Error 1
memcpy(new->value, k->value, sizeof(k->value));
...
new->prev = NULL;
new->next = NULL;
return;
}
/**
* Creates a new doubly-linked list with the successors of node k.
* Allocates memory for node "first" (the first node of the list)
*/
void successors(node *k, node *first) {
node *tmp1, *tmp2;
...
newSuccessor(k, start, 0,0, 0,1);
newSuccessor(k, tmp1, 0,0, 1,0);
appendToList(start, tmp1);
return;
}
int depthFirstSearch(node *k, int target[3][3], int depth) {
...
node *firstNode, *tempNode;
successors(k, firstNode);
while (firstNode != NULL) {
int res = depthFirstSearch(firstNode, target, depth+1);
if (res == 1) {
// Target was found
return erg;
}
*tempNode = *firstNode->next;
free(firstNode); // !!! Error 2
*firstNode = *tempNode;
}
}
int main(int argc, char* argv[]) {
depth_max = 3;
int target[3][3];
...
node *k = (node *) malloc(sizeof(node));
...
depthFirstSearch(k, target, 0);
}
Error 2: free(firstNode);
Here, the computer gives me this error:
Quote:
9223: symbol=free; lookup in file=./depthfirstsearch [0]
9223: symbol=free; lookup in file=/lib/tls/i686/cmov/libc.so.6 [0]
*** glibc detected *** ./depthfirstsearch: free(): invalid pointer: 0xb7fb7ff4 ***
Segmentation fault (core dumped)
Well, so I marked this line as a comment ;)
Error 1: *new = *tempNode;
This produces after some tries (not at the first try) this message:
Quote:
Segmentation fault (core dumped)
I guess there must be something wrong with the pointers. FYI I ran the program in Ubuntu linux 7.04.
Any help would be greatly appreciated.