[SOLVED] Problems with dynamic memory in CCS (calloc and malloc)

Status
Not open for further replies.

Plateau

Junior Member level 3
Joined
Jan 4, 2012
Messages
30
Helped
2
Reputation
4
Reaction score
2
Trophy points
1,288
Activity points
1,553
HiHo, friends, are you all fine?

After so much problems in handling the interrupts, I've decided to use the KBHIT approach (https://www.edaboard.com/threads/277650/). Now, everything is ok but I have a doubt about dynamic memory use.

In my code, I have a pair of routines to write and read data from EEPROM. Both are based on native CCS EEPROM routines.

The read routine is:

Code:
char* leStringEEPROM(int8 low, int8 high){
	//char* texto = calloc((high-low),sizeof(char));
	char texto[12];
	int8 i,y=0;	
	
	for(i=low;i<high;i++){
		texto[y] = (char)read_int16_eeprom(i);
		y++;
	}
	return texto;
}

I don't know why, but this routine only works well when I declare the variable 'TEXTO' as a static length array. When I use the dynamic array associated with calloc, the array TEXTO always returns with wrong length (per example, if the right length would be 10, it returns 12).

Can anybody help me to solve this issue?

Regards,

Pedro Rosa.
 

Hi Pedro,

How do you detemine the length of the array "texto"?
Your code does not guarantee tah it is a null-terminated string.
Regards

Z
 

Hi Pedro,

How do you detemine the length of the array "texto"?
Your code does not guarantee tah it is a null-terminated string.
Regards

Z

Hiho, Zorro, are you fine?

At the first moment, I determined the size of array using the calloc instruction:

Code:
char* texto = calloc((high-low),sizeof(char));

But it never worked well...the array 'TEXTO' always returns the wrong size.

Looking your reply about my code doesn't ensure the null-terminated character and some related doubts in other places around the internet, I've tried to increase by 1 Byte the size of array in the calloc instruction (i.e

Code:
char* texto = calloc((high-low)[B][COLOR="#FF0000"]+1[/COLOR][/B],sizeof(char));

and now it seems to work. :-D )

One more time, thank you so much.

Best regards,

Pedro Rosa!
 

Hiho, Zorro, are you fine?
Yes. Thanks, Pedro.

...the array 'TEXTO' always returns the wrong size.
About that... which is that return value?
For example, if strlen(texto) would be used, length would be determined looking at the first null character.


Because now you have always a null character at the end (calloc returns the block of memory initialized to zero).

Regards

Z
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…