0

I'm trying to create an array of a struct but I don't know it size at the beginning.

struct MyStruct** thing;
size_t thing_len = 0;
thing = (struct MyStruct**) malloc(thing_len * sizeof(struct MyStruct*));
//...
thing_len += 1
thing = (struct MyStruct**) realloc(thing_len * sizeof(struct MyStruct*));

When I do that thing gets the type MyStruct* instead of MyStruct** and contains 0x0. But when I do

struct MyStruct* thing;
size_t thing_len = 0;
thing = malloc(thing_len * sizeof(struct MyStruct));
//...
thing_len += 1
thing = realloc(thing_len * sizeof(struct MyStruct));

It works!!

I don't know if it changes something but I am using -ansi and -pedantic options.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

4

In your code

  realloc(thing_len * sizeof(struct MyStruct*));

is a wrong call to the function. You must use the format [Check the man page.]

 realloc(<old pointer>, new size);

That said, a format like

 oldPointer = realloc (oldPointer, newSize);

is a very dangerous piece of code. In case realloc() fails, you'll end up losing the original pointer also!!

The prescribed way to use realloc() is

 tempPointer = realloc (oldPointer, newSize);  //store the return
 if (tempPointer)                              // is it success?
 {
        oldPointer = tempPointer;              // cool, put it back to the variable you want
 }
             //--> here, whether or not realloc is success, you still got a _valid_ pointer.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • In many cases, a program will be doomed to die a miserable death in any case where `realloc()` would fail. Including an explicit `if (!oldPointer) out_of_memory_error()` may be better than dying from a SIGSEGV, but keeping a copy of the old pointer around in cases where code is going to die anyway isn't necessarily helpful. It's too bad there aren't standard functions for "malloc_or_die", "realloc_or_die", etc. since they could eliminate the need for a lot of redundant error-handling code. – supercat Oct 30 '17 at 16:28