3

When calling a function b_destroy, the program crashes before it reaches the end of the function. The function looks like this:

void b_destroy(Buffer * const pBD){
#ifdef DEBUG
printf("IN DESTROY\n");
printf("BUFFER ADDRESS %d\n",pBD);
printf("HEAD ADDRESS %d\n",pBD->ca_head);
#endif
if(pBD != NULL || pBD->ca_head != NULL){
    if (pBD->ca_head != NULL)
        free(pBD->ca_head);
    if (pBD != NULL)
        free(pBD);
}
#ifdef DEBUG
    printf("EXITING DESTROY\n");
#endif
}

I know the pointers aren't NULL because I'm able to print out the memory location. Any ideas why it crashes?

9
  • If you need any more info let me know Sep 24, 2013 at 15:06
  • Just because a pointer is non-null doesn't mean it's valid. Sep 24, 2013 at 15:08
  • 4
    Your logic is wrong in there. Think about what happens if pBD is indeed null.
    – Mat
    Sep 24, 2013 at 15:08
  • Calling free doesn't set the pointer to NULL so the memory that the pointers are pointing to might have already been freed.
    – Simon
    Sep 24, 2013 at 15:09
  • only place I'm calling free is from this function, and it only gets called once. Sep 24, 2013 at 15:11

3 Answers 3

2

When you free some pointer you should always set the pointer to NULL immediately. If you don't they might lead to crash else where in the program. That might be the case in your program. Also always print addresses using %x (for memory addresses) format specifier and not %d (for signed integers)

Need to look at your complete program to find the problem. Try setting pointer to NULL after freeing at all places that might fix your problem.

2
  • Well the driver code that calls this function sets the pointer to NULL after it's called. Sep 24, 2013 at 15:27
  • Agree about setting pointer to NULL after freeing at all places. Note: OP function will not allow that here for some questionable reason pBD is const. Sep 24, 2013 at 17:41
2

Think carefully about your logic here:

if(pBD != NULL || pBD->ca_head != NULL)

If pBD is 0, then your logic is:

if(0 || 0->ca_head != NULL) { // that 0-> will seg fault

}

Maybe you want something like:

if (pBD && pBD->ca_head)
    free(pBD->ca_head);
if (pBD)
    free(pBD);
0
1

It doesn't matter that the address is not null, but rather that the data there has not already been freed. You need to search elsewhere to see if the same memory has already been freed, as Free doesn't set the given pointer to null afterwords.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.