Example: Modifying the third letter of a string is a
#include <stdlib.h>#include<string.h>#include<stdio.h>#pragmaWarning (disable:4996)voidMain () {Char*p = (Char*)malloc( -); strcpy (P,"123456789"); P= p +2; *p ='a'; Free(P); System ("Pause");}
Run, VS reported the following error:
This problem occurs because the C language stipulates that if you want to release memory, you must get the first address of the memory to release it.
The P pointer is shifted before it is released and no longer points to the first address, so the program occurs crash. WORKAROUND: Simply save the address of the first element for release.
#include <stdlib.h>#include<string.h>#include<stdio.h>#pragmaWarning (disable:4996)voidMain () {Char*p = (Char*)malloc( -); strcpy (P,"123456789"); Char*pheader =p; P= p +2; *p ='a'; printf ("%s\n", Pheader); Free(Pheader); System ("Pause");}
Operation Result:
C + + Error NOTE-If you want to free memory, you must get the first address of the memory to release