0
int size = 2;
string *s = new string[size];
s[0] = "First"; 
s[1] = "Second";

//reallocating memory and increasing its size
size++;
s = (string*)realloc(s, size * sizeof(string));//here is an error
s[2] = "Third";


// Error: realloc():invalid pointer\
//        Aborted core is dumped

For example the same approach with dynamic int array which works fine

int size = 5;
int *a = new int[size];
for(int i = 0; i < size; i++) a[i] = i*(3);
++size;
a = (int*)realloc(a, (size)*sizeof(int));
a[size-1] = 132321;

Question: How realloc is different for string and int???

Note!

  1. I was thinking which tag is more suitable for my post c or c++ tag. Since I use string I decided to use c++ tag.
  2. I know that I can use vector, but my assignment is about using dynamic string array without using a vector.
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
raksa
  • 21
  • 6
  • 5
    `realloc` is for a pointer obtained from `malloc` or `realloc`. Not for a pointer obtained from `new`. The complement to `new` is `delete` and it has no `realloc` parallel. – JohnFilleau Jan 03 '22 at 03:29
  • @JohnFilleau but, how it comes that for (int) it works fine? (P.S Thank you, I have solved my problem) – raksa Jan 03 '22 at 03:36
  • 2
    @raksa — it’s just bad luck that it seems to work fine. – Pete Becker Jan 03 '22 at 03:52
  • the `malloc` family and `new` *may* use the same underlying memory allocation, or they may not. Your `realloc` may have just extended the present memory address, or it may have created a new memory block and copied your integers. It's easier to copy plain old data types (integers) than C++ objects (`string`). For the actual answer, you'll have to look at your compiler's `realloc`, `new`, and `string` implementations. – JohnFilleau Jan 03 '22 at 03:54
  • Also note that @PeteBecker 's comment above isn't a typo. Undefined behavior acting normally is very unlucky. In software development we prefer to know right away if something is wrong. Otherwise the silent error may also be deadly. – JohnFilleau Jan 03 '22 at 03:55
  • *but my assignment is about using dynamic string array without using a vector.* -- They're still teaching C++ this way in school (assuming this is a school assignment), even after `std::vector` has been part of C++ for 24 years now? Obviously, whoever gave this assignment never mentioned that `realloc` does *not* create objects, so usage of it for non-POD types like `std::string` will not work. – PaulMcKenzie Jan 03 '22 at 05:12

0 Answers0