Hai all,

I ran into a strange issue I never experienced before. Pointers are passed to function, the function allocates memory to them with calloc, and right before the return sanity checks if the pointers still != NULL. That check succeeds, but upon returning and sanity checking in the calling function, all pointers == NULL.

The code is pretty big, so I won't copypaste it all in here but instead i've attached them.

For those unfamiliar with OpenGL: The compiler line for this is:
gcc.exe BowViceJet.c -o BowViceJet.exe -lopengl32 -lglu32 -lgdi32 -Wall

The function I'm talking about is loadObj. As you can see, right before returning it checks:

if(vertices == NULL || normals == NULL || verttext == NULL || triangleindex == NULL || trianglenormals == NULL || quadindex == NULL || quadnormals == NULL){
    printf("Failed to allocate enough memory, exiting...\n");
    exit(1);
  }
  return 0;
}

and in the calling function it checks again:

loadObj("C:\\ObjTest.obj", vertices, normals, triangleindex, quadindex, &trianglecount, &quadcount);
  if(vertices == NULL || normals == NULL || triangleindex == NULL || quadindex == NULL){
    printf("Error! One of the essential pointers == NULL!");
    exit(1);
  }

and there it happily prints the message and exits.

How come? :(

Thanks in advance,
Nick

PS: Also included "ObjTest.txt" so you can experience it in it's full glory. Heh. ;) Don't forget to either adjust source code to load "ObjTest.txt" or change extension to ".obj" so that it reads "ObjTest.obj".

Recommended Answers

All 2 Replies

That's because the memory address contained in the pointer is lost when the function is popped off the stack. In other words, you can modify the value that the pointer points to, but you can't modify the memory address that the pointer holds (well, you can, but the change won't have any effect on the pointer in the parent function).

The solution to this would be to use a pointer of a pointer.

Ooooooooooh, really newb mistake right there, haha. Thanks for *pointing* it out. No pun intended ofc. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.