I'm writing an application and am having problems with passing a dynamically created array through pointers to the calling function.
I create a pointer in the main to contain the dynamically generated array, and an int to contain the length of that array. I pass those to the readNDEF() function. There it allocates memory based on the read of the needed memory, and reads bytes into the generated array.
Followed a lot of the answers givin here on similar questions but none seem to fix it, of give other errors (eg stack smashing)
int main(void) {
uint8_t *recordPTR; //creating pointer
uint8_t length=0; //creating length variable
readNDEF(recordPTR, &length);
int i;
for (i=0;i<1;i++){
printf("%x ",*(recordPTR+i)); //segmentation fault happens here
}
}
bool readNDEF(uint8_t *messagePTR, uint8_t *messageLength){
int NDEFlength;
if(!(NDEFlength=getNDEFmessageLength())<0){ //get length
closeSession();
return false;
}
uint8_t tempLength=0x00|NDEFlength;
messagePTR = malloc(tempLength*sizeof(uint8_t)+5); //+5 overhead for the rest of the frame
if(messagePTR == NULL){ //check if mallok ok
return false;
}
if(!ReadBinary(0x0002, (uint8_t)0x00|NDEFlength, messagePTR)){ //read NDEF memory
closeSession();
return false;
}
messagePTR++; //skip first byte in the array
closeSession();
*messageLength = tempLength;
//print the array (Works, data correct)
int i;
for (i=0;i<tempLength;i++){
printf("%02x ",*(messagePTR+i));
}
return true;
}
The length returns like it should, but the array itself when enumerating it in the for loop gives a segmentation fault. Using an other way I could enumerate it without the fault, but the data was not correct (random data) probably because it was out of scope after returnign from the function.