Incidentally, Click_here made a typo. His example should have been...
Sorry, grumpy is correct - I missed that one.
No - Because if I change the data type of command_string, I won't have to go through and change all the chars to this new data type.
Consider this example which may send a pattern from a microcontroller (using stdout) with limited space (so the memory needs to be freed and and table recalculated)
Try types char*, then unsigned char*, and then unsigned int* to fix the bug as comments note.
Code:
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE1 0xFF
#define DATA_SIZE2 0x1FF
int main(void)
{
//char *myDynamicArray = NULL;
//Bug found: Negative numbers were being printed
//Change to "unsigned char"
//unsigned char *myDynamicArray = NULL;
//Bug found: Overflow detected on "unsigned char" type
// Change to type unsigned int
unsigned int *myDynamicArray = NULL;
if( (myDynamicArray = malloc(DATA_SIZE1 * sizeof(*myDynamicArray))) != NULL)
{
int i = 0;
for(i=0; i<DATA_SIZE1; i++)
{
myDynamicArray[i] = i;
printf("%d ", myDynamicArray[i]);
}
free(myDynamicArray);
}
else
{
//Send predefined error code string
puts("<Err=0xE101>");
}
putchar('\n');
/***************************************/
// Here there may be lots of processing
//
// Lots of memory will be needed
//
// That is why myDynamicArray needs to
// be freed...
/***************************************/
if( (myDynamicArray = malloc(DATA_SIZE2 * sizeof(*myDynamicArray))) != NULL)
{
int i = 0;
for(i=0; i<DATA_SIZE2; i += 2)
{
myDynamicArray[i] = i;
printf("%d ", myDynamicArray[i]);
}
free(myDynamicArray);
}
else
{
//Send predefined error code string
puts("<Err=0xE102>");
}
/***************************************/
// Here there may be lots of processing
//
// Lots of memory will be needed
//
// That is why myDynamicArray needs to
// be freed...
/***************************************/
return EXIT_SUCCESS;
}