A pointer can either own a resource (malloc) or point a resource already owned by another entity. When you do p="string";
, you are creating a const char *
to which you assign the character pointer p
, there by leaking the malloc'd memory in the previous line, in the latter, you're just replacing the contents inside the malloc'd memory; former is a bug/issue, latter is not. It is to be noted that although it's bad practise to leak resources/memory, it isn't the reason behind the hang.
The reason you get a hang is because the edit you make in your C code under the hood tries to edit you're program's read-only memory space (const char *
variables are created as immutable byte arrays in this segment of the program memory). when does c++ allocate/deallocate string literals explains further on this.
As for passing the required bytes to malloc
, a good practise to avoid using type in the expression:
const size_t count_required = 10;
char *p = malloc(sizeof(*p) * count_required);
// changing p's type to int* would also work without editing the malloc argument
when the type of p is changed to, say, float
, int
or any other type the expression will continue to work fine without any changes.