I strongly recommend re-reading Richard Bos' response, but from your
comments about it I thought you might benefit from a response that more
directly addresses your questions.
Hi all,
void main()
{
char *fp;
fp=malloc(26);
strcpy(fp,"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
fp[10]='\0';
free(fp);
}
Please refer the program for my questions..
1. Can any one tell me if would i assign '\0' at middle of
dynamically assigned memory area will i get memory leak.. ??
Writing a null character into dynamically allocated memory will not, in
itself, cause a memory leak.
The problem with your code, on the other hand, is that your call to
strcpy() writes a null character to fp[26], which is one position past
the end of the allocated memory. As a result of that error, the behavior
of your entire program is undefined, which means that anything could go
wrong A memory leak is very definitely a possibility from making that
kind of mistake, but most of the other possible consequences of that
mistake are much worse than memory leaks.
2 . Will "free()" delete all the memory which allocated by
dynamically even NULL values has been added in middle of that.??
Your code wrote one null value at a position one past the end of the
allocated memory, and a second null character at the beginning of the
allocation. It didn't write any null characters into the middle of the
allocation. Calling free() does not delete memory.
Writing null characters into the allocated memory has no affect on the
behavior of free(), regardless of where you write them, so long as it is
inside the allocation. Because of your mistake, the call to free() could
do anything, including sending insulting e-mail to your mother. However,
if you hadn't written a null character one past the end of the allocated
memory, the behavior of free() would have been to deallocate the memory,
making it available for further allocation.
3. How let i know that will i get memory leak in a program?? any
compiler option are there ?? Can i use splint tool ?
Memory leaks occur at run time, not at compile time. Compilers can't
catch memory leaks, though some of the better ones can catch some of the
mistakes that result in memory leaks.
There are compilers that provide options that provide run-time help with
leak detection. There are debugging versions of the malloc() family of
functions. There are tools which run your program inside an environment
that allows you to monitor memory allocations and detect links. However,
in order to recommend an appropriate tool, we need to know what compiler
and operating system you're using.