Thomas
Thomas

Reputation: 43

C passing dynamic array through pointer (Segmentation Fault)

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.

Upvotes: 0

Views: 507

Answers (1)

Ashalynd
Ashalynd

Reputation: 12563

Your readNDEF method allocates memory for an object inside that method (because argument of the type pointer, as any other argument in C, is passed by value). Hence the pointer outside has not been changed, and the memory allocated within that function was lost (a memory leak). You need to pass a pointer-to-pointer in order to achieve what you want:

bool readNDEF(uint8_t **messagePTR, uint8_t *messageLength){
///
*messagePTR =  malloc(tempLength*sizeof(uint8_t)+5);
}

and call it accordingly:

readNDEF(&recordPTR, &length);

Upvotes: 1

Related Questions