This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Loop Gets Stuck at Particular Index



I'm using the TM4C1294XL board with CCS. The following code gets stuck at iteration number 255 ( i.e. when TestTempInt = 255).

Array x_frame;
InitNullArray(&x_frame);

for(TestTempInt=n;TestTempInt<=(n+499);TestTempInt++){
AddConsToArr(&x_frame,X[TestTempInt]);
printf("%d\n",TestTempInt);
}

The Array structure and Function declarations are as follows:

InitialArrayValue = -999;

typedef struct ArrayStruct{ float * array; size_t used; size_t size; }Array; // INITIALIZE NULL ARRAY void InitNullArray(Array * ArrayPtr){ ArrayPtr->array=NULL; freeArray(ArrayPtr); ArrayPtr->array = (float *)malloc(1 * sizeof(float)); ArrayPtr->used = 0; ArrayPtr->size = 1; ArrayPtr->array[0] = InitialArrayValue; } // ADD CONSTANT TO ARRAY ( A=[A;C] ) void AddConsToArr(Array * InitialArray, float NewValue){ insertArray(InitialArray,NewValue); } // INSERT ELEMENT INTO ARRAY void insertArray(Array *a, float element) { if (a->used+1 == a->size) { a->size *= 2; a->array = (float *)realloc(a->array, a->size * sizeof(float)); } a->array[(a->used)+1] = element; a->used=a->used+1; }

Is this a matter of Heap or Stack size ? If so, how much can I allocate to each ? If not, what other thing should I be looking at. Please advise. Thank you.

P.S: The Array Structure itself is made so that it mimics the array indexing used in MATLAB.

  • Ahmad Shah said:
    Is this a matter of Heap or Stack size ?

    Given that program dynamically increases the size of the array, I would say the problem is lack of heap.

    If realloc() or malloc() are unable to allocate the requested memory they will return a NULL pointer. The program doesn't check the return from realloc() or malloc(), and assumes the allocation succeeded. If realoc() or malloc() return a NULL pointer the program will generate a hard-fault when it tries to write to the array, which will cause the program to get stuck. This is because NULL is address zero which is flash in a TM4C1294 which causes a hard-fault if the program tries to write directly to the flash.

    Ahmad Shah said:
    If so, how much can I allocate to each ?

    It depends upon how much free SRAM there is.

  • Since you know the size of the array before you start the loop, you should consider adding a reserve method to set the size of the array before the loop to minimize reallocations, which are relatively expensive. See C++ std::vector::reserve(). Besides the expense, if the array is large relative to the size of the heap, you'll never be able to grow the array after it gets to be at least one third the size of the heap.