Search code examples
cpointersfree

How to cast a pointer in the free() function?


"warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] "

the problem is here free((void*)c_array[i]); if you can explain me how to solve the problem, thank you!

static char* create_char_array() {
char* array = (char*) malloc(sizeof(char)*4);

array[0] = 'd';
array[1] = 'a';
array[2] = 'f';
array[3] = 'b';

return array;
}


static void delete_test_char_array(char* c_array, int len) {
  for(int i = 0; i < len; ++i) {
    free((char*)c_array[i]);
   }
free(c_array);
}

static void test_char_increasing_insertion_sort() {
char* array = create_char_array();
generic_increasing_insertion_sort((void**)array, 4, (ElementsCmp) compare_chars);

TEST_ASSERT_EQUAL('a', array[0]);
TEST_ASSERT_EQUAL('b', array[1]);
TEST_ASSERT_EQUAL('d', array[2]);
TEST_ASSERT_EQUAL('f', array[3]);

delete_test_char_array(array, 4);
 }

Solution

  • You're trying to free individual characters. The free function only accepts pointers that were returned from malloc.

    You only call malloc once, so only call free once.

    static void delete_test_char_array(char* c_array) {
        free(c_array);
    }