將內存分配給另一個函數中的雙指針,因此我需要使用指針指向指針。我得到一個異常,當我使用sscanf時,我不知道爲什麼。下面是代碼的一小部分。這是早期工作時,它是在同一個函數,我只需要使用雙指針,但現在即時通訊重構代碼和使用三重指針即時通訊有這個問題。在另一個函數中傳遞三指針來分配內存,sscanf異常
typedef float vector[3]
int mainLoaderFunc() {
char* memory = NULL;
size_t size = loadFile(fileName, &memory); // load model file into memory, this works, tested and true
// create vector arrays
vector *vertexArray = NULL;
vector *normalArray = NULL;
vector *textureArray = NULL;
loadArrays(size, memory, &vertexArray, &normalArray, &textureArray);
// do other stuff with arrays
}
void loadArrays(size_t size, char *memory, vector **vertexArray, vector **normalArray, vector **textureArray) {
int numVerts = 0;
int numNormals = 0;
int numTextures = 0;
char* p = memory; // pointer to start of memory
char* e = memory + size; // pointer to end of memory
// count verts, normals, textures for memory allocation
while (p != e) {
if (memcmp(p, "vn", 2) == 0) {
numNormals++;
} else if (memcmp(p, "vt", 2) == 0) {
numTextures++;
} else if (memcmp(p, "v", 1) == 0) {
numVerts++;
}
while (*p++ != (char) 0x0A);
}
// allocate memory for vector arrays
*vertexArray = new vector[numVerts];
*normalArray = new vector[numNormals];
*textureArray = new vector[numTextures];
p = memory;
int vertexIndex = 0;
int normalIndex = 0;
int textureIndex = 0; //*** IF BREAK POINT HERE: NO EXCEPTION
// load data from memory into arrays
while (p != e) {
if (memcmp(p, "vn", 2) == 0) {
sscanf(p, "vn %f %f %f", &normalArray[normalIndex][0], &normalArray[normalIndex][1], &normalArray[normalIndex][2]);
normalIndex++;
} else if (memcmp(p, "vt", 2) == 0) {
sscanf(p, "vt %f %f", &textureArray[textureIndex][0], &textureArray[textureIndex][1]);
textureIndex++;
} else if (memcmp(p, "v", 1) == 0) {
sscanf(p, "v %f %f %f", &vertexArray[vertexIndex][0], &vertexArray[vertexIndex][1], &vertexArray[vertexIndex][2]);
vertexIndex++;
}
while (*p++ != (char) 0x0A);
}
}
一旦代碼打sscanf的一部分,我得到異常:
Unhandled exception at 0x5e9cf2dc (msvcr100d.dll) in derp.exe: 0xC0000005: Access violation writing location 0xcccccccc.
如果你使用的是C++,並且你正在使用三指針,那麼你幾乎肯定會出錯...... – 2011-12-21 21:24:59
這段代碼是如何到達sscanf部分的?當(p!= e)循環之後,當然你需要重置p來指向內存,否則第二個while(p!= e)循環將不會進入一次,因爲直到p == e 。 – 2011-12-21 21:36:50
另外,將p前進到'\ n'(0x0a)是非常危險的,然後回到假設你還沒有達到p == e。也許你直接通過e尋找'\ n' – 2011-12-21 21:38:48