1
I was learning a little bit more about dynamic allocation in C++ on the Internet, and a teacher’s code caught my attention.
It is a code made to spend only the necessary memory and not have "blank 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, the memory allocation in C++ is done through the new
, not using malloc()
.
Another thing that caught my attention was that this code would not be invading memory since it was only allocated a space of 2 bytes?
I didn’t understand your question about the allocation of memory in c/c++,the new operator is c++,it is more abstract than malloc since you don’t need to specify the size in bytes of your dynamic allocation
– Gabriel Ribeiro
My question is whether this code is invading memory, since it has only been allocated 2 bytes for the variable "name" and whether this code is the correct way to allocate memory in C++, since it appears to be a C code, excluding "Cout".
– Vitor Carlos
Allocation in c++ is done with
new
, but no one prevents you from usingmalloc
, although I shouldn’t. Since I speak in "shouldn’t", you shouldn’t usegets
in c++ which has been marked as obsolete in c++11 and removed in c++14. But what is your specific question ?– Isac
Well, this code is theoretically made to use only the amount of memory needed, for example, the user typed a string with 15 characters, it will consume only the data needed to store 15 characters + the string finalizer. However, I believe that you are only allocating a space of 2 bytes, that is, 1 character + the string finalizer. Is this code actually invading memory? Or are you fulfilling your proposal without invading memory?
– Vitor Carlos
You’ve allocated 2 bytes, so if you save more than 2 bytes, you’re invading memory. Conclusion: anything that the user places with more than one letter (the other is for the terminator) represents invalid access in memory, in the buffer overflow case and consequent undefined behavior.
– Isac
Thank you very much, so in fact it is what I thought, is invading memory. Apparently I will have to change my source of study, some suggestion?
– Vitor Carlos
To c tag wiki already has a suggestion of good books on the topic. Good studies.
– Isac
Each program executed in RAM has its own space for its execution, and this space is divided by some areas, the main ones being the stack, this space of 2 bytes is being allocated in the space destined to it,what could happen is the use of the total heap of the program,to release this allocated memory
– Gabriel Ribeiro