I have what looks to me an innocent cycle which iterates on elements of an array whose type is unknown at compile time; my array is named mesh->vertices and is a pointer to void. Depending on the truth value of mesh->textured I need to consider the array differently. Incidentally, the code in the if and the else in the code segment below is similar, but I do need to distinguish two cases.
void TransformMesh(struct Mesh *mesh, struct Matrix4 *t)
{
for (int i = 0; i < mesh->nVertices; ++i)
{
if (mesh->textured)
{
struct TexturedVertex *ptr = ((struct TexturedVertex *)mesh->vertices) + i;
ptr[i].position = MatrixPointMultiply3(t, &ptr->position);
ptr[i].normal = MatrixPointMultiply3(t, &ptr->normal);
}
else
{
struct Vertex *ptr = ((struct Vertex *)mesh->vertices) + i;
ptr[i].position = MatrixPointMultiply3(t, &ptr->position);
ptr[i].normal = MatrixPointMultiply3(t, &ptr->normal);
}
}
}
I guess I created the project with the Automatic Reference Counting option, thinking that it would not have affected C code, but now I feel like I’m wrong (by the way, how can I check which option I chose?).
Well, it looks like this function is doing something wrong with another array, called mesh->triangles, probably freeing it. When I try to use the vector I get an EXC_BAD_ACCESS error:
glDrawElements(GL_TRIANGLES, mesh->nTriangles * 3, GL_UNSIGNED_INT, mesh->triangles);
It looks like iterating on the mesh->vertices elements, casting them and doing the pointer arithmetic, is corrupting the memory. I think my problem is ARC, so I tried to do what described here but with no luck.
EDIT:
The code above was wrong, as pointed out by Conrad Shultz; the following is correct:
ptr->position = MatrixPointMultiply3(t, &ptr->position);
ptr->normal = MatrixPointMultiply3(t, &ptr->normal);
I seriously doubt ARC has anything to do with this – ARC only manages Objective-C objects. (It doesn’t even know how to handle Core Foundation types, which leads to the requirement for using the
__bridge...keywords.)I’m struggling to understand your code. Admittedly, I don’t do a great deal of straight C programming, but I don’t get what you’re trying to do by adding
itoptr, which is presumably the pointer arithmetic of which you speak.Are you trying to just access the
ithstruct TexturedVertexinmesh->vertices? If so, just use yourptr[i]construct as written.It looks to me like you are doing arithmetic such that
ptrends up pointing to theithstruct TexturedVertex, then by accessingptr[i]you are readingielements past theithstruct TexturedVertex. IfnVerticesrefers to the count ofvertices(as would seem logical, given the name and C array conventions), you are then reading past the end ofvertices, a classic buffer overflow error, which would unsurprisingly lead to EXC_BAD_ACCESS and all sorts of other fun errors.