Function can not allocate memory for a pointer in C

-2

I have a struct which is called "visitor" and I want to write function which allocates the memory for my pointer to this struct ...

this Codes works:

visitor *visitorPtr = NULL;
int visitorCounter = 0;
visitorPtr = realloc(visitorPtr, ((visitorCounter++) * sizeof(visitor)));

but now I wanted to put this functionality to a function

void getMoreSpace(void *ptr, unsigned int counter)
{
    counter++;
    ptr = realloc(ptr, counter * sizeof(visitor));

    if (ptr == NULL)
    {
        printf("\n Error allocating memory! \n");
        return EXIT_FAILURE;
    }
}

//Call in MAIN:
getMoreSpace(visitorPtr, visitorCounter);

Unfortunately it seems not to work because I cant create data for this pointer and get this Error when I make that for that struct: Exception thrown at 0x0FDAE559 (ucrtbased.dll) in My-C-Project.exe: 0xC0000005: Access violation writing location 0x00000000.

c
pointers
realloc
asked on Stack Overflow Apr 3, 2019 by BlindRob

1 Answer

1

visitorPtr is passed as value to getMoreSpace function. Thus any changes done to ptr within the function will not update the vistorPtr in main.

What you need is call the function by reference as below.

void getMoreSpace(void **ptr, unsigned int counter)
{
    counter++;
    *ptr = realloc(*ptr, counter * sizeof(visitor));

    if (*ptr == NULL)
    {
        printf("\n Error allocating memory! \n");
    }
}

And from main you call as below.

getMoreSpace(&visitorPtr, visitorCounter);
if (visitorPtr)
   ...do stuff....
answered on Stack Overflow Apr 3, 2019 by kiran Biradar • edited Apr 3, 2019 by kiran Biradar

User contributions licensed under CC BY-SA 3.0