0

I know how to do it with heap memory, but I try to get rid of any heap memory allocation in my code.

I cannot use any library which can help me, it means: <string> for example.

How can I do it with using stack memory allocation?

int main(void) {
    class Animal {
        unsigned char nameLength;
        unsigned char name[];

        setName(unsigned char name[]) {
            memcpy(this->name, name, this->length * sizeof(unsigned char));
        }
    }

    Animal dog;

    // The value '4' isn't constant, it depends on received data from socket
    dog.nameLength = 4;

    // Right now I know how many elements will be in dog.name array

    unsigned char randomName[dog.nameLength];

    // Here will be a for loop, but just for example:
    randomName[0] = "B";
    randomName[1] = "e";
    randomName[2] = "n";
    randomName[3] = "/0";

    dog.setName(randomName);

    // Expected output: dog.name = "Ben\0"
}

The for loop will look like:

unsigned char i;
for (i = 0; i < (dog.nameLength-1); i++) {
    randomName[i] = packet[i];
}
randomName[i] = 0;

1 Answers1

0

Your code has multiple issues, please break it down into multiple questions for each problem you are having.

But for the main issue: in general it is a very bad idea to do what you are trying to do (allocate dynamically on the stack), this is exactly what heap allocations are for.

Also, standard C++ does not allow this. There are, however, compiler extensions you could use: Why no variable size array in stack? and linux has alloca: http://man7.org/linux/man-pages/man3/alloca.3.html & C++ How to allocate memory dynamically on stack?

But, again, do not do this unless you really need to and you understand what you are doing.

Also, please listen to the commenters about how to ask a question and provide a minimal example.

DeducibleSteak
  • 1,398
  • 11
  • 23