C++ – Dynamic Memory Reallocation using realloc

c++memory-leaksmemory-management

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.

Best Solution

In

g = "ab";

you make g point to a chunk located in static storage, not on heap, then in

g = (char*) realloc (g, sizeof(char) * 200); 

you try to call realloc() with that address belonging outside the heap. This is undefined behaviour and crashes your program. You can call realloc() only with addresses returned by malloc() or realloc() (or null pointer).

The problem is that you meant this:

strcpy( g, "ab" ); 

but mistakenly wrote this:

g = "ab";

The former would work allright - g is initially set to an address returned by malloc().

There's one more problem - you allocate too little memory initially. You should allocate an extra byte for the null terminator.

Related Question