# function definition with structure node

• 12-10-2001
Peachy
function definition with structure node
I need to write a definition of a function with all the following points to be addressed:

1. function name is Problem
2. it receives a parameter named b of the struct node * type
3. it creates a new dynamic variable with "p" pointing to it and with contents the same as those of the node to which "b" points to
4. it returns the address of the newly created code

not sure if I have this right, please critique as necessary:

Code:

void Problem(struct node * b)
{
struct node * p = (struct node *) malloc (sizeof (struct node));
p = b;
returns p;
}

• 12-10-2001
master5001
This pretty much accomplishes what you wanted, however, this could have memory leaks. Lets say your program works like this:
Code:

void Problem(struct node * b){
struct node *p = (struct node *) malloc (sizeof (struct node));
p = b;
returns p;
}
int main(void){
struct node *mem_leak = (struct node *)malloc(sizeof(struct node));
Problem(mem_leak);
return 0;
}

Okay, now if you are not very experienced the memory leak probably went under your radar but I'll explain. You allocated a block of memory to struct node *mem_leak via malloc. Immediately afterward you pointed it to a different block of data. The other block of data that it was pointing to in the first place didn't just disappear. So what you may want to do is free a struct before passing it in toe Problem.
• 12-10-2001
Sayeh
Also, you want your prototype to allow you to return a pointer.

---------------

typedef struct
{
int data1;
long data2;
}node,*nodeP;

nodeP Problem(nodeP);
int main(void);

int main(void)
{
nodeP rootNode;
nodeP newNode;

rootNode = 0L; /* init to known state */
newNode = 0L;

rootNode = malloc(sizeof(node)); /* allocate */
if(rootNode)
{
newNode = Problem(rootNode); /* duplicate root node */
if(newNode)
{
free(NewNode);
newNode = 0L;
};

free(rootNode);
rootNode = 0L;
};

return(0);
}

nodeP Problem(nodeP b);
{
nodeP theNodeP;

theNodeP = 0L; /* init to known state */
theNodeP = malloc(sizeof(node)); /* allocate it */
if(theNodeP)
{
theNodeP->data1 = b->data1; /* copy struct contents (brute force) */
theNodeP->data2 = b->data2;
};

return(theNodeP);
}

------------------

anyway, something like the above.

enjoy.