cancel
Showing results for 
Search instead for 
Did you mean: 

[Solved] Infinite loop without "Warning: iteration N invokes undefined behavior", using pointers to get data from a function

Not applicable

I am citing this error here, just in case someone else has this type of occurrence.

uint8_t data1[5];
 
for(uint8_t x = 0; x < 8; x++)
{
	data1[x] = 0;
}

When using an array in a count loop above the limits of the array, the compiler can report a warning:

warning: iteration 5 invokes undefined behavior

But if pointers are used, the compiler may not warn and the program may enter an infinite loop:

CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
CH10 data1 = 10
.
.
.

Since the expected operation should look something like this:

CH0 data1 = 10
CH1 data1 = 10
CH2 data1 = 10
CH3 data1 = 10
CH4 data1 = 10
CH5 data1 = 10
CH6 data1 = 10
CH7 data1 = 10

The code that caused the loop:

/* USER CODE BEGIN 0 */
uint8_t foo1(uint8_t *data2)
{
	uint8_t data3[8];
 
	foo2(data3, 0);
 
	*data2 = data3[0];
 
	return 0;
}
 
uint8_t foo2(uint8_t* data4, uint8_t channel)
{
	for (uint8_t i = 0; i < 9; i++)
	{
		data4[i] = 10;
	}
 
	return 0;
}
/* USER CODE END 0 */
 
/* USER CODE BEGIN 2 */
for(uint8_t x = 0; x < 8; x++)
{
	uint8_t data1 = 0;
 
	foo1(&data1);
 
	UsrLog("CH%d data1 = %d", x, data1);
 
	HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
 
	HAL_Delay(500);
}
	/* USER CODE END 2 */

Note that the function foo1 passes an array[8] and the function foo2 tries to work with an array with 9 elements.

uint8_t foo1(uint8_t *data2)
{
	uint8_t data3[8]; <-------- limit: 8
 
	foo2(data3, 0);
 
	*data2 = data3[0];
 
	return 0; // error
}
 
uint8_t foo2(uint8_t* data4, uint8_t channel)
{
	for (uint8_t i = 0; i < 9; i++) <----- limit: 9
	{
		data4[i] = 10;
	}
 
	return 0;
}

0 REPLIES 0