0

Is this valid in c?

int  func()
{                                                               
        static int *p = NULL;
        p = realloc(p, 20);                             
        return 0;
}

I want to use this in recursion so every time the func function is called if there is already allocated memory it will be reallocated and if there is non(first call) it will be allocated instead.

overkill
  • 11
  • 2
  • 3
    `p` is not a null pointer -- it's uninitialized. I think you want `static int*p;` – Paul Hankin May 14 '21 at 15:47
  • 1
    What you describe _is_ valid, but your code does _not_ match what you describe because you did not initialize `p` at all. – paddy May 14 '21 at 15:47
  • 1
    You should change `int *p;` to `static int *p;` to have it do what you want. `static` make the variable retained between multiple calls of `func` and initialized to zero by default. – MikeCAT May 14 '21 at 15:49
  • 3
    Instead of static I would rather pass the pointer down to recursive calls as a parameter. This will make the function pure and reentrant. Don't forget to free it. – Eugene Sh. May 14 '21 at 15:53
  • okay I did fix the code now – overkill May 14 '21 at 16:03
  • That works - assuming you have no thread contention issues that need to be resolved with a mutex. Unless you're doing low-level stuff, this is a code smell. Note that an empty parameter list specification: `func ()` should *not* be used in modern C. Use: `func (void)` – Brett Hale May 14 '21 at 16:20
  • `is called if there is already allocated memory it will be reallocated` Why would you want to reallocate to the same `20` amount of memory? The memory is yours, just use it. – KamilCuk May 14 '21 at 16:33

1 Answers1

1

Using realloc() with NULL for the first argument is legal and realloc(NULL, size) is equivalent to malloc(size), but your code is illegal because it is using an value of uninitialized non-static local variable p, which is indeterminate.

Quote from N1570 7.22.3.5 The realloc function:

#include <stdlib.h>
void *realloc(void *ptr, size_t size);

3 If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70