How to cast the address of a pointer generically while conforming to the C standard

前端 未结 5 2094
迷失自我
迷失自我 2020-12-17 19:00

It is common to assign pointers with allocations using an implicit function-return void * conversion, just like malloc()\'s:

void *malloc(size_t size);
int *         


        
5条回答
  •  没有蜡笔的小新
    2020-12-17 19:38

    I think your code might provide some interesting problems due to casting void* to void** and dereferencing it. According to GCC this is not a problem but sometimes GCC lies. You can try

    #include 
    #include 
    
    int allocate_memory(void **p, size_t s) {
        if ( ( *p = malloc(s) ) == NULL ) {
            fprintf(stderr, "Error: malloc();");
            return -1;
        }
        return 0;
    }
    
    int main(void) {
        int *pi = NULL;
        if ( allocate_memory((void**) &pi, sizeof *pi) == 0 ) {
            printf("pi: %p;\n", (void *) pi);
        }
        return 0;
    }
    

    Note that in your original code you had to cast int** to void* (implicit) and then explicitly cast to void** which could really confuse your compiler. There might still be an aliasing problem due to the fact that main's int *pi is accessed as and assigned a void pointer. However, a quick scan of the C11 standard is inconclusive in that regard (see http://open-std.org/JTC1/SC22/WG14/).

提交回复
热议问题