Like a dynamic realloc global variable with C

Ok, this is my first C program since it is "hello wolrd" and I need help with realloc. I have a dynamic array defined as a global variable.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

double *close = NULL;
unsigned int closesize = 0;

And I want to increase the array in the method. But I get a seg failure error. I tried this as follows:

  void addInputParamReal(
     OCIExtProcContext *ctx
    //,unsigned int paramIndex
    //,OCINumber *value
    ,double value
  )
  {
    double dtemp;
    double **myclose = &close; // last try, make a pointer to my outside array
    //OCINumberToDouble(ctx,value,&dtemp);
    dtemp = 12.4; //just now

    //Not good
    *myclose = (double *) realloc (*myclose,(closesize+1) * sizeof(double));
    close[closesize++] = dtemp;
  }

Could you help me? thanks Chris

+3
source share
3 answers

An extension of 1 each time will be somewhat ineffective. Usually you expand by a piece (a fixed size or a percentage of the current size), and then track the physical size ( closesize) separately from the index of the array (name it closeindex):

if (closeindex == closesize)
{
  double *tmp = realloc(close, sizeof *tmp * (closesize + EXTENT));
  if (tmp)
  {
    close = tmp;
    closesize += EXTENT;
  }
  else
  {
    // panic
  }
}
close[closeindex++] = ...;

You can find a way to make this a little more elegant, I'm sure.

+1

reallocs NULL, - . , Linux NULL, , . malloc().

, 1 . , , , . , , .

0

As Fred Nurk said in the comments above, I add this as an answer:

The variable should not be called close ... now I renamed it and it works .... but my vi does not highlight "close" :-)

- edit1:
what i did now:

  void addInputParamReal(
     OCIExtProcContext *ctx
    ,OCINumber *value
  )
  {
    // do we need more mem?
    if (bar1size==0)
    {
      bar1close = (TA_Real *) malloc(initsize * sizeof(TA_Real));
      bar1size=initsize;
    }
    else if (bar1size<bar1idx || bar1size == 65536)
    {
      raise_exception(ctx,__LINE__,"addInputParamReal,memory allocation failed");
      return;
    }
    else if (bar1size==bar1idx)
    {
      bar1close = (TA_Real *) realloc (bar1close, (bar1idx*2) * sizeof(TA_Real));
      bar1size = bar1idx*2;
    }

    //assign value
    double dtemp;
    OCINumberToDouble(ctx,value,&dtemp);
    bar1close[bar1idx++] = (TA_Real) dtemp;
  }
0
source

Source: https://habr.com/ru/post/1789032/


All Articles