Jay
Jay

Reputation: 24905

Why is the below code giving "dereferencing type-punned pointer will break strict aliasing rules" & How to fix it?

 int test_malloc(void **ptr, size_t size)
 {
    (*ptr) = malloc(size);
    return 0;
 }

 int test_app()
 {
   char *data = NULL;
   int ret = 0;
   ret = test_malloc((void **)&data, 100);
 }

Compiler: gcc 4.1.2

Among others, I am using -O2 & -Wall which are I think are turning on some options which checks for this.

Upvotes: 1

Views: 520

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215557

You cannot do what you're trying to do in C; it's invalid code. If you want to use void * to return generic pointers, the only way to do so is the return value. This is because void * converts to any pointer type, and any pointer type converts to void *, but void ** does not convert to a pointer to some other type of pointer, nor do pointers to other pointer types convert to void **.

Upvotes: 2

Timo
Timo

Reputation: 5176

You have a variable of type char*, and in test_malloc you are modifying it through an lvalue of type void *, which breaks strict aliasing rules.

You could solve it like this:

 int test_app()
 {
   char *data = NULL;
   void *void_data = NULL;
   int ret = 0;
   ret = test_malloc(&void_data, 100);
   data = (char*)void_data;
 }

But even better is to make test_malloc return void* to avoid problems like this.

Upvotes: 3

Oki Sallata
Oki Sallata

Reputation: 374

I try like this one works fine

void * test_malloc(int size)
{
    void *mem = malloc(size);
    if (mem == NULL)
    {
        printf("ERROR: test_malloc %d\n", size);
    }
    return mem;
}

 int test_app()
 {
   char *data;
   int ret = 0;
   data = test_malloc(100);

   if(data != NULL)
         free(data);
 }

Upvotes: 1

Related Questions