I have simple code,
#include "stdafx.h"
#include <malloc.h>
int main()
{
char *p = (char*) malloc(10);
p = "Hello";
free(p);
return 0;
}
This code is giving run time exception while terminating. Below is error snippiest,
Microsoft Visual C++ Debug Library
Debug Assertion Failed!
Program: …\my documents\visual studio 2010\Projects\samC\Debug\samC.exe
File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
Line: 1322
Expression: _CrtIsValidHeapPointer(pUserData)
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
This is how you write a string in the memory allocated by malloc to a char pointer.
Replace the line
with the
strcpyone & your program will work fine.You also need to
mallocreturns a pointer to allocated memory. Say the address is 95000 (just a random number I pulled out).So after the malloc – p will hold the address
95000The p containing
95000is the memory address which needs to be passed to free when you are done with the memory.However, the next line
p = "Hello";puts the address of the string literal “Hello” (which say exists at address25000) into p.So when you execute
free(p)you are trying to free25000which wasn’t not allocated by malloc.OTOH, when you
strcpy, you copy the string “Hello” into the address starting at p (i.e.95000).premains95000after the strcpy.And
free(p)frees the right memory.You can also avoid the
mallocand useHowever, in this method, you cannot modify the string.
i.e. if after this you do
*p = 'B'to change the string toBello, it becomes an undefined operation. This is not the case in themallocway.If instead, you use
or
you get a modifiable string which need not be
freed.