Can anyone help me, why I\'m getting an error message while trying to free the allocated memory: Heap corruption detected. CTR detected the application wrote the memory after en
From man strcpy(3):
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.
So you need to reserve 6
bytes 5
for the string and 1
for the NULL
byte
char *s = new char [6];
strcpy(s, "hello");
You've corrupted s2 pointer by
strcpy(s, "hello");
Because s has size 5, while you've missed that strcpy includes string terminator.
Your initial string s
is only five characters long so can't be null terminated. "hello"
will be copied by strcpy
including the null-terminator but you'll have overrun the buffer. The strlen
needs it to be null terminated so if the null's not there, you'll have problems. Try changing this line:
char *s = new char [6];
Better still, prefer std::string
to C style string functions - they're just as efficient and a lot safer and easier to use. Also, try to avoid new
and delete
unless you really have to use them. The problems you're getting are very common and can easily be avoided.
strcpy
includes the null terminator; strlen
does not. Write:
char *s1 = new char [strlen(s) + 1];
You need to specify char *s1 = new char [strlen(s) + 1];
to make room for the '\0'
which terminates the string.
new char [strlen(s)];
does not count the closing \0
character, so your buffer is too short by one character.