In the code below I am getting an EXC_BAD_ACCESS error for no apparent reason when I call print vertex. The pointers point to the exact same location, but somehow it crashes when I pass in vp2.
#include <stdio.h>
typedef struct {
float x;
float y;
float z;
} Vertex;
void printVertex(Vertex *v);
int main (int argc, const char * argv[])
{
Vertex v = {1,0,2};
int memL = (int)&v;
Vertex *vp = &v;
printf("Memory Location: %i\n", memL);
printf("Memory Pointed to by Pointer: %i\n", (int)vp);
Vertex *vp2 = (Vertex *)memL;
printf("Memory Pointed to by Pointer from memory location: %i\n", (int)vp2);
printVertex(vp); // Executes normally
printVertex(vp2); // EXC_BAD_ACCESS
return 0;
}
void printVertex(Vertex *v)
{
printf("Vertex[%f,%f,%f]\n", v->x, v->y, v->z); // EXC_BAD_ACCESS when vp2 passed in
}
Output:
Memory Location: 1606416816
Memory Pointed to by Pointer: 1606416816
Memory Pointed to by Pointer from memory location: 1606416816
Vertex[1.000000,0.000000,2.000000]
EXC_BAD_ACCESS Error
Might be truncating the adddress of
v. You could try:to see if this is the case. This should not crash if truncation is a problem.