On Jun 17, 7:57 am, (e-mail address removed) wrote:
that code invokes undefined behavior. I've already explained to Bart
why, but he doesn't seem to appreciate my advice.
You can do this:
#include <stdio.h>
int send(char *str);
int main(void) {
char s[512];
sprintf(s, "p", malloc(1024));
send(s);
return 0;
}
int send(char *str) {
void *p;
sscanf(str, "%p", &p);
free(p);
I think this free(p) will show undefined behavior. According to my
understanding we should not try to free any memory using function
“free()” if the memory is not obtained through malloc or realloc .
In the above code pointer “p” (void *p) is not obtained using malloc
or realloc . So would it not cause undefined behavior ?
return 0;
}
sscanf() will presumably fail the conversion and an uninitialized
pointer will be freed. Not (void *)"p" or anything like that.
It was my mistake. I thought it would work, but apparently it doesn't.
I have a poor understanding of C.
You are too hard on yourself. You rejected and earlier correction of
the sprintf format to "%p" saying that was not what you meant, but I
can't see what else you could mean. For the record, unless I have got
it all wrong, this is perfectly well defined:
#include <stdio.h>
#include <stdlib.h>
void send(char *str);
int main(void)
{
char s[512];
sprintf(s, "%p", malloc(1024));
send(s);
return 0;
}
void send(char *str)
{
void *p;
sscanf(str, "%p", &p);
free(p);
}
and does not have any memory leaks. If you mean that what you were
proposing would not work when the part doing the sprintf and the part
doing the sscanf have separate address spaces, then yes you are right
that it won't work. All %p does is represent the pointer as text in a
reversible way.