Re: memory leakage problem
- From: Simon Biber <news@xxxxxxxxx>
- Date: Tue, 31 Oct 2006 12:15:37 +1100
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.
.
- References:
- memory leakage problem
- From: chets
- memory leakage problem
- Prev by Date: Re: not writing to file
- Next by Date: Re: C Interview Questions
- Previous by thread: Re: memory leakage problem
- Next by thread: finding how much the file system is full, from a C program?
- Index(es):
Relevant Pages
|
|