Dynamic allocation in C++

I was learning a little more about dynamic allocation in C++ on the internet, and a code from a teacher caught my eye.

Is a code made to spend only the necessary memory and have no "white space", storing only the amount of characters used.


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main ()
{
    char *nome;
    nome = (char*)malloc(sizeof(char)+1);

    gets(nome);

    cout << nome << endl;

    return 0;
}

As far as I know, Memory Allocation in C++ is done through new, not using malloc().

Another thing that caught my attention was that this code does not would it be invading memory since only a space of 2 bytes has been allocated?

Author: Maniero, 2019-07-16

1 answers

If you were learning to allocate memory like this on the internet, run out. Almost all the existing content on the internet about programming is bad, something saved and for a layman it is very difficult to identify what is bad because he does not know yet, so it is better to look only for sources that are admittedly reliable.

In this case your concern should not be this, this code should be just like this:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string nome;
    cin >> nome;
    cout << nome << endl;
}

See working on ideone. And no repl.it. also I put on GitHub for future reference .

In fact, if you were to make an allocation you should use new and not malloc(), and even then only in very specific code, probably a library, in normal code this is rarer, the most common is the type do their own memory management or use smart pointers .

If you were to use malloc() you should use 2, you don't have to use sizeof(char) because it it's always 1.

This code has too many errors and should be completely ignored, even it allocates space for only 1 character and will corrupt the memory.

 1
Author: Maniero, 2019-07-23 14:40:26