I am learning C and in a specific code ,I have assigned a command line argument to a character array whose memory is allocated dynamically
char *ptr;
ptr=(char *)malloc(500*sizeof(char));
ptr=argv[argc-2];
and after completing the code and freeing the memory
free(ptr);
I am getting an error
*** Error in `./a': free(): invalid pointer: 0x00007fff00c0c604 ***
can any one help me where is my mistake
There are a few misconceptions.
"I have assigned a command line argument to a character array".
ptr=argv[argc-2];
No you did not. You assigned the value of a pointer (to a character sequence from commandline arguments) to a pointer variable (losing the pointer to malloced memory which was previously stored there).
"after completing the code [...] freeing the memory"
free(ptr);
Not really, what you are doing is calling free()
on a pointer which was NOT previously malloced (because of having lost it with previous mistake).
That is the explanation of what happens.
The comment by Retired Ninja hints at a solution, though I recommend to use strncpy()
instead, to copy the commandline argument to the memory you have allocated. It keeps the pointer to allocated memory (instead of overwriting it) and that in turn allows to free it later.