简体   繁体   中英

C Programming malloc macro issue

Using Microsoft Visual Studio 2010:

Can I write this type of macro in C? I cannot get it to work myself.

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))

If I write it like this, it works:

#define MEM_ALLOC(type, nElements) (testFloat = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT))

This is how I am using it:

#define CACHE_ALIGNMENT 16
#define INDEX 7
#define MEM_ALLOC(type, nElements) (type = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT))
#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))
#define MEM_DEALLOC_PTR(type) (_aligned_free(type))

int _tmain(int argc, _TCHAR* argv[])
{
    float* testFloat;

    //MEM_ALLOC_C(testFloat, INDEX);    // Problem here.

    MEM_ALLOC(testFloat, INDEX);        // works

    //testFloat = (float*)_aligned_malloc(INDEX * sizeof(float), CACHE_ALIGNMENT);  // works

    testFloat[0] = (float)12;

    //MEM_DEALLOC_PTR(testFloat);       // If we call de-alloc before printing, the value is not 12.
                                    // De-alloc seems to work?

    printf("Value at [%d] = %f \n", 0, testFloat[0]);

    getchar();

    MEM_DEALLOC_PTR(testFloat);

return 0;
}

Thanks for any help.

think about the replacment:

type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)

becomes

testFloat = (testFloat*)_aligned_malloc(INDEX * sizeof(testFloat), CACHE_ALIGNMENT)
.

There is no such thing as testFloat* .

In pure C there is no need to cast the result of malloc. Therefore you can just do:

 #define MEM_ALLOC_C(var, nElements) (var = _aligned_malloc(nElements * sizeof(*var), CACHE_ALIGNMENT)) 

The problem in your MEM_ALLOC_C() macro is that you're using the type parameter as both a type and a an lvalue. that can't work:

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))
//                                    ^^^^    ^^^^                                     ^^^^
//                                   lvalue   type                                     type

Note how in your working version you had to use a variable name where the lvalue goes and a type in the other spots.

If you really want to have a macro like this, why not just use it like a function and assign the result to a pointer instead of hiding the assignment inside the macro:

#define MEM_ALLOC_C(type, nElements) ((type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))

testFloat = MEM_ALLOC_C(float, INDEX);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM