I’m currently attempting to learn the C side of C++.
I attempt to malloc a chunk of memory for a char array of 256 and then I assigned it a char* "Hello World!" but when I come to free the object I get an error.
Can anyone please explain to me the error.
#include <exception>
#include <stdexcept>
#include <iostream>
int main()
{
void* charVoidPointer = malloc( sizeof(char) * 256 ) ;
charVoidPointer = "Hello World";
std::cout << (char *)charVoidPointer;
free (charVoidPointer);
}
“Hello World” is statically allocated by the compiler. It is part of the program and exists at some place addressable by the program; call it address 12.
charVoidPointer initially points to some place allocated for you by malloc; call it address 98.
charVoidPointer = “Hello …” causes charVoidPointer to point to the data in your program; address 12. You lose track of address 98 previously contained in charVoidPointer.
And you can’t free memory not allocated by malloc.
To demonstrate more literally what I mean:
What you meant was:
Edit: Example of addressing memory for other types
Experiment; Change the type from int to long, or double, or some complex type.