Re: memory leakage problem



chets wrote:
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;
}

--
Simon.
.



Relevant Pages

  • Re: Comments ok?
    ... char or is a null pointer. ... invokes undefined behavior. ... provide NULL or a valid pointer to a char, ...
    (comp.lang.c)
  • Re: Comment on trim string function please
    ... char *p1, *p2, ch; ... The order doesn't matter if the test against p is trivial:) I'd like ... Yes, even p1 doesn't equal to NULL, it's not a valid pointer ... Here you can still generate in invalid pointer. ...
    (comp.lang.c)
  • memory leakage problem
    ... where declaration is like this ... char **p; ... in one file after mallocing q and want to free q ... in another program, it does not do that, memory leakage. ...
    (comp.lang.c)
  • pointer assignments
    ... where declaration is like this ... char **p; ... in one file after mallocing q and want to free q ... in another program, it does not do that, memory leakage. ...
    (comp.unix.aix)
  • memory leakage problem
    ... where declaration is like this ... char **p; ... in one file after mallocing q and want to free q ... in another program, it does not do that, memory leakage. ...
    (comp.unix.programmer)