[Solved] Array created using Malloc() remains sizeof(int)

I am trying to use malloc to create a tab in which I can store Freeman Code Values (an algorithm to identify a pattern). I declared my malloc that way :

int *ptr=NULL;
ptr=(int*) malloc(LengthNeeded*sizeof(int));

So using the following Macro :

#define SIZEOF_ARRAY(x)  (sizeof(x)/sizeof((x)[0]))

I was expecting to get LengthNeeded however I get a 1, so my Array is the sizeof(int). By curiosity I tried changing the type of my array to int8_t to see wether I still get 1. But I get 4 what confirms the fact that my array is defined as sizeof(int) no matter what the type of my pointer was at the beginning.
Thinking it might be a space issue I used realloc in order to have my array rewritten to where there is enough space :

int * ptr1 = (int *) malloc( sizeof(int) );
ptr1 = (int *) realloc( ptr1, 10 * sizeof(int) );

Same issue. Browsing the forums I found out it was necessary to check whether the malloc was not NULL so I did :

if(ptr==NULL){
    exit(0);
  }

And there my code exits the loop depending of the way I declare my array :

int * ptr1 = (int *) malloc( sizeof(int) );//No problem it keeps running

int *ptr=NULL;
ptr=(int*) malloc(LengthNeeded*sizeof(int));//exit loops

I do not quite get what is wrong here, I followed the whole openclassroom tutorial on malloc() and wandered on many forums to look for different solutions? I found a thread advising people to go for the C++ new() and delete() functions but I am the kind of person who will stay tilted if I do not understand where I am wrong :sweat:. I do not think it matters but the board I am using is the PortentaH7.

sizeof(int) is not 1 so there must be some other problem

I meant sizeof(Array)/sizeof(Array[0])=1
sizeof(Array[0])==sizeof(int)
So my array only contains 1 int, Am I wrong?

Sizeof(int *) is 2 (on an avr)
Sizeof cannot be used on dynamically allocated memory.

Ok I get it. Sizeof cannot be used to know the size of the allocated memory. So I defined a structure where I store the size of the array as well as the array :

struct remember_the_size
{
    size_t len;
    int * arr;
};


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  
  struct remember_the_size a = { 10, NULL };
  a.arr =(int*) malloc(a.len * sizeof *a.arr);
  int i;
  for(i=0;i<a.len;i++){
    Serial.println(a.arr[i]);
  }
  Serial.print("Size :");
  Serial.println(a.len);
  free(a.arr);
}

However according to what I ve read there is nothing that bares me to read beyond the malloc region, like :

Serial.println(a.arr[a.len+1]);

So how can I be sure that I allocated an array of 10 in elements and that I am not just overwriting data stored beyond the malloc?? Afterall the default value of the data after the malloc is the data previously written there.

EDIT: I use calloc for now but it is an unstable solution because some values could have been at zero from the very beginning...

EDIT : That works fine c - How detect malloc failure? - Stack Overflow

You cannot use SIZEOF_ARRAY to tell you the size of an array you created using malloc. You're getting a size of one because your macro is using the size of the pointer to the "mallocated" memory to calculate its result. The pointer is two bytes, as is sizeof int, so 2/2 gives one.

Good for you for find your answer! :+1:

you also could create a class if you really wanted to...

something like this maybe:

class DyArr {
  private:
    int _Size;
    int *arr;

  public:
    int ArrSize() {
      if (arr == NULL) return -1; //was unable to allocate memory for buffer
      else return _Size;
    }

    int Get(int index) //retrieve value from created array
    {
      if ((arr != NULL) && (index < _Size)) return arr[index];
    }

    int Put(int val, int index) //insert value into array
    {
      if (arr == NULL) return -1; //was unable to allocate memory for buffer
      else if (index < _Size) {
        arr[index] = val;
        return 1;
      }
      return -2;
    }

    //constructor
    DyArr(int Size)
    {
      _Size = Size;
      arr = malloc(sizeof(int) * _Size);
    }

    //deconstructor
    ~DyArr()
    {
      if (arr != NULL) free(arr);
    }

};


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  DyArr myArray(10);

  if (myArray.ArrSize() != -1) {
    for (int i = 0; i < myArray.ArrSize(); i++) {
      myArray.Put(i, i);
    }

    Serial.print("Size :");
    Serial.println(myArray.ArrSize());
    for (int i = 0; i < myArray.ArrSize(); i++) {
      Serial.print(myArray.Get(i));
      Serial.print(" ");
    }
  }
}

void loop() {
}

Output:

Size :10
0 1 2 3 4 5 6 7 8 9

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.