Will it leak the memory?

C

Chris Dollin

Mark said:
Chris said:
KG wrote:

Hi,
I do have a question.

int main()
{
char *p = (char *)malloc(9);

strcpy(p,"TajMahal");

p++;

free(p);

}

Does this program results in memory leak?


It results in undefined behaviour. The only legal arguments to `free`
are null and a pointer returned from malloc that hasn't been freed.

There's no way of telling what that does from the C standard.

If you omit the `p++`, then the program terminates with memory
still allocated. [snip]

Did you really mean this?

I really meant it.

Now, of course, I see it as nonsense. What I intended to say was more
like "If you omit the `p++` /and the free/", then ...", but a demon
flew out of my nose and erased the "and the free" bit.

Thanks for catching my idiocy, Mark.
 
S

Serve Lau

Mark Bluemel said:
You haven't included a valid prototype for malloc and your cast has hidden
a potentially value compiler diagnostic.


This results in undefined behaviour. The address you passed to free()
isn't an address of a a block of space allocated with malloc(), calloc()
or realloc().


If you're lucky the program will crash. If you're very unlucky, the
computer will grow arms, produce a knife and stab you.
<http://www.xkcd.com/293/>

I find this stuff highly offensive, we need a picture of a dildo coming out
of the machine doing naughty things
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top