简体   繁体   中英

Why don't my simple code work in C++?

Error in function realloc(): invalid pointer

int indZero = 0; 

int *perZero=NULL;

int zero = 0;//Initialization


ProcessBit(zero,&indZero,&perZero);// Call function

void ProcessBit(int num,int *ind,int **mas)

{

mas=(int**)realloc(&mas,((*ind))*sizeof(int));// Error

mas[num-1]++;//it's correct line

}

A few problems:

  • The first argument to realloc is the original pointer (or NULL ).

  • Your ProcessBit doesn't really emulate pass-by-reference correctly.

  • You can use a negative index.

  • mas is a pointer to a pointer to int , but you use it as a pointer to int .

A "fixed" version might look something like this:

void ProcessBit(int num, int *ind, int **mas)
{
    int *temp = realloc(*mas, (*ind + 1) * sizeof(int));
    if (temp == NULL)
    {
        // TODO: Handle error
        // TODO: return or exit(EXIT_FAILURE)
    }

    *mas = temp;

    (*mas)[*ind] = 0;  // Initial initialization

    if (num > 0)
    {
        (*mas)[num - 1]++;
    }

    ++*ind;  // Increase the size
}

Now, if this really was C++ (as you tagged your question) then you should be using std::vector instead, which would solve almost all your problems with much simpler code.

The parameters are wrong. Since you are trying to realloc a NULL pointer it should behave like malloc; however, the header declared in cstdlib is

void* realloc( void* ptr, std::size_t new_size );

The formal parameter mas is already the address of the pointer, so the call should be

*mas=(int*)realloc(*mas,((*ind))*sizeof(int));
(*mas)[num-1]++;

Since realloc handles and returns pointers by copy , not by reference.

You are passing the address of the memory location where the address of a memory location (NULL) is stored to your ProcessBit function, and then the address of that location to the realloc function. The function tries to reallocate memory where the variable mac is stored, on the stack. No wonder it's an invalid pointer.

By passing &mac you are simply taking a step in the wrong direction while dereferencing pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM