Search code examples
csegmentation-faultfree

Segfaults when trying to free pointer


I have a code like this

void find_groupings ()

  int *bandwidths;
  int *execution_time;

  bandwidths = (int *)malloc(sizeof(int)*node_count); // node_count is glbl
  execution_time = (int *)malloc(sizeof(int)*node_count);
  //other mallocs, other code etc

  while (condition) {
    // lot of code
    find_bandwidths(bandwidths);
    find_execution_time(execution_time);
    //lot of code
  }

  free(bandwidths);
  free(execution_time);

}

code segfaults at line "free(execution_time);"

Thread 1 "vx_tutorial_exe" received signal SIGSEGV, Segmentation fault.
0xf7dd0cd9 in _int_free (av=0xf7f15780 <main_arena>, p=<optimized out>, have_lock=0) at malloc.c:4005
4005    malloc.c: No such file or directory.

I can guarantee that "execution_time" doesn't go out of bound inside the find_execution_time() I believe I free every malloc I do in the code

Also found that pointer value for execution_time is the same just before it crashes at the free() using gdb

tried valgrind but, it doesn't help since the program segfaults

What could be the problem here ?


Solution

  • the whole issue was, in a malloc I had casted it with a wrong type

    for buffers I had malloced it as

    buffers  = (int *)malloc(sizeof(int)*node_count);
    

    It should have been

    buffers  = (buffer *)malloc(sizeof(buffer)*node_count);
    

    buffer is a structure type in my code.

    It's so weird that it crashed in a way that is impossible to find out based on error messages.

    Thank you Jeremy! and pm100