memory leakage problem

C

chets

Hi all
Can anyone tell me what is the difference between:-

*p=q; and p=&q; in C

where declaration is like this
char **p;
char *q;

Because if I do *p=q; in one file after mallocing q and want to free q
in another program, it does not do that, memory leakage.

if I do p=&q; than it works.

So if anyone can tell me how these are internally treated than it can
be helpful.
Thanks in advance.;
 
W

Walter Roberson

Can anyone tell me what is the difference between:-
*p=q; and p=&q; in C

*p=q means to take the current value of q, do any necessary type
or value conversions, and store the result in the memory
pointed to by the pointer p, which must have already been given a value
(i.e., must already point to storage.)

p=&q means to take the address of q and store it in the pointer variable
p, thus setting p to point to an object (i.e., q). p does not need to
have a value beforehand, and any value it had before is ignored.
 
S

Simon Biber

chets said:
Hi all
Can anyone tell me what is the difference between:-

*p=q; and p=&q; in C

*p = q; /* the value of q is copied into the memory location
referred to by the value of p. */

In *p = q, if the value of p was not already a valid pointer, then the
expression causes undefined behaviour. The value of p remains unchanged.

p = &q; /* the address of q is copied into the pointer variable p */

In p = &q, it doesn't matter whether the value of p was already a valid
pointer or not. Its old value is not used but is replaced.

The above explanation applies whenever the expressions are valid. That
is, when the type of p is 'pointer to' the type of q.
where declaration is like this
char **p;
char *q;

These declarations are OK. Of course, p must be set to a valid pointer
first, if you want to use *p = q.
Because if I do *p=q; in one file after mallocing q and want to free q
in another program, it does not do that, memory leakage.

You can't free memory in one program that was allocated in a different
program. But you can do it in separate translation units (C files) that
are linked together into a single program.
if I do p=&q; than it works.

You need to provide a complete example program to demonstrate what's not
working.

This works:

/* foo.c */

#include <stdlib.h>

extern char **p;

void do_free(void)
{
free(*p); /* free q through *p */
free(p); /* free p itself */
}


/* bar.c */

#include <stdlib.h>

char **p;

int main(void)
{
char *q = malloc(sizeof *q);
p = malloc(sizeof *p);
if(!p || !q) exit(EXIT_FAILURE);

*p = q;

do_free();

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top