【发布时间】:2014-08-27 13:16:08
【问题描述】:
我正在编写一个应用程序,但在通过指向调用函数的指针传递动态创建的数组时遇到问题。
我在 main 中创建了一个指针来包含动态生成的数组,以及一个 int 来包含该数组的长度。我将它们传递给 readNDEF() 函数。它在那里根据所需内存的读取分配内存,并将字节读取到生成的数组中。
这里有很多关于类似问题的答案,但似乎没有一个可以解决它,给出其他错误(例如堆栈粉碎)
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;
}
长度按原样返回,但在 for 循环中枚举数组时,数组本身会出现分段错误。使用另一种方式我可以枚举它而不会出错,但数据不正确(随机数据)可能是因为它在函数返回后超出范围。
【问题讨论】:
标签: c arrays pointers segmentation-fault malloc