FotelPL
FotelPL

Reputation: 23

char* in struct memory allocation

So I have a struct like this (in fact it's bigger):

struct _setup {
    char* selfName;
    int8_t zone;
    char* selfSSID;
    char* selfWPA2;
}

I'm using it to hold config for my device; JSON was an idea but it's taking much resources and time to proces.
I want to allocate 32 chars for each char*. What will be happening to this struct:
1. Filled with data of unknown length BUT shorter than 32 bytes
2. Saved to EEPROM
3. Read from EEPROM to another struct (same layout)

I've tried malloc and new inside the struct but it didn't work.
What is the correct way to allocate memory and write data to struct?

Upvotes: 2

Views: 1037

Answers (2)

hamed
hamed

Reputation: 481

You have two option for allocating memory for struct members:

1- Static memory allocation:

struct _setup {
    char selfName[32];
    int8_t zone;
    char selfSSID[32];
    char selfWPA2[32];
}

Static allocation recommended if your allocation size is short and you know that size at compile time. otherwise use dynamic allocation.

static allocation is faster than dynamic allocation. but if you want to create huge count of object from this struct you may get Stackoverflow exception. becasue you may utilize all stack space. (if your real array size is about 32, Stackoverflow exception is improbable)

2- Dynamic Allocation :

struct _setup {
    char* selfName;
    int8_t zone;
    char* selfSSID;
    char* selfWPA2;
    _setup()
    {
         selfName= (char*)malloc(sizeof(char)*32);
         selfSSID= (char*)malloc(sizeof(char)*32);
         selfWPA2= (char*)malloc(sizeof(char)*32);
    }
    ~_setup()
    {
         free(selfName);
         free(selfSSID);
         free(selfWPA2);
    }
}

you can use Dynamic allocation with malloc or new operators. but you should remember that you must free() these dynamic memories after using them. I placed free in distructor, you can put those everywhere you want.

Upvotes: 0

Aman
Aman

Reputation: 706

You should ideally use std::string and not char* if in c++

For your code, this could be more readable way along with destructor:

struct _setup {
    char* selfName;
    int8_t zone;
    char* selfSSID;
    char* selfWPA2;
    _setup()
    {
         selfName = new char[32];
         selfSSID = new char[32];
         selfWPA2 = new char[32]; //Or this for direct value: new char [strlen("hello") + 1];
        //strcpy(selfWPA2, "hello");
    }

    ~_setup()
    {
        delete selfName;
        delete selfSSID;
        delete selfWPA2;

    }
};

Upvotes: 1

Related Questions