Search code examples
cpointersstructdynamic-allocationcode-composer

C dynamic allocation of struct


I have a problem trying to dynamically allocate a struct in C:

typedef struct
{
    uint8_t wifiSSID[30];
    uint8_t wifiPassword[20];
}
tWifiPair;


typedef struct
{
    tWifiPair *wifiNetworks; // this needs to become an array with 2 elements
    // if I do the above like this tWifiPair wifiNetworks[1] - all works fine
}
tEEPROMSettings;

tEEPROMSettings gEEPROMSettings;

int main()
{
    gEEPROMSettings.wifiNetworks = (tWifiPair *)calloc(2, sizeof(tWifiPair));

    // .... writing to gEEPROMSettings.wifiNetworks[0].wifiSSID crashes the program, unfortunately I can't see the error, but the compiler doesn't throw any errors/warnings
}

If this tWifiPair *wifiNetworks is done staticly - tWifiPair wifiNetworks[1] - it works fine, but I need to do it dynamically and possibly change it while the program is running.

This is running on an embedded platform - ARM tm4c1294ncpdt, compiler is CCS6.

Can you point me to where the error is? Thanks!


Solution

  • You need to check the return value of calloc to make sure it succeeded.

    On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.

    From this reference

    Now, if calloc is failing, that is another question.

    Updating with info from comments for others reading:

    This appears to be an embedded system, which may have a small heap configured. calloc does return NULL, so the allocation is failing. Depending on your compiler/linker, you may need to adjust a linker script, scatter file, or project options to change the heap size.