Hello All,
I am learning C++. I am trying to learn this dynamic memory allocation. In the below code I am trying to allocate memory using malloc
and realloc
.
int main (void) {
char *g = (char*) malloc (sizeof(char) * 2);
g = "ab";
g = (char*) realloc (g, sizeof(char) * 200);
strcpy (g, "cdefg");
cout << g << endl;
return 0;
}
I get segmentation fault error when I execute this code.
I've seen other SO threads recommending to use either vector
or new
instead of using above approach. Since, I am trying to learn this approach, so these answers does not applies to my question.
I've encountered a scenario where this approach will be well fitted, for example, If I am reading a raw text file using ifstream.read
function and reading, let's say 1024bytes of it. Now, If I want to make sure I am not reading a word which is broken due to 1024bytes size I have to read further from that position using ifstream.get
to reach until a space character is found. In this scenario, I need to adjust the buffer (which is of 1024) slightly more. My intention is to use realloc
here to assign some more memory to it.
Please feel free to correct me if I am wrong anywhere.