Search code examples
cstructuredynamic-memory-allocation

Error while allocating memory to a structure pointer


I am trying to allocate memory for my structure pointer which I am declaring globally. But I am getting this error --> error: initializer element is not constant

typedef struct A {
    uint32_t arr[30][4096];
    uint32_t var1;
    uint8_t  var2;
    bool     var3;
}B;

B *x = (B*)malloc(sizeof(B));

Can anyone explain me where I am doing it wrong. Also, instead than dynamic memory allocation, is there a direct way to allocate memory to structure pointers? Thanks in advance.


Solution

  • You cannot use malloc in global scope like declaring a variable. You must use constant to init a variable in global scope.

    You can use it (it is a function call) inside a function

    #include <stdio.h>
    #include <stdbool.h>
    #include <stdint.h>
    #include <stdlib.h>
    
    typedef struct {
        uint32_t arr[30][4096];
        uint32_t var1;
        uint8_t  var2;
        bool     var3;
    }A;
    
    A *x;
    
    int main()
    {
        x = malloc(sizeof(A));
    
        if (x != NULL)
        {
            free(x);
        }
    
        return 0;
    }
    

    Form the c99 standard.

    6.7.8 Initialization

    1. All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

    The constants are defined as follows:

    6.4.4 Constants

    Syntax

    constant:

    integer-constant       (e.g. 4, 42L)
    floating-constant      (e.g. 0.345, .7)
    enumeration-constant   (stuff in enums)
    character-constant     (e.g. 'c', '\0')
    

    The standard defines constant expressions as follows:

    6.6 Constant expressions

    (7) More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

    — an arithmetic constant expression,

    — a null pointer constant,

    — an address constant, or

    — an address constant for an object type plus or minus an integer constant expression.

    (8) An arithmetic constant expression shall have an arithmetic type and shall only have operands that are integer constants, floating constants, enumeration constants, character constants, and sizeof expressions. Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types, except as part of an operand to a sizeof operator whose result is an integer constant.