Particle.function uses String to accept parameter value. Possible to use char array instead?

The Particle.function uses String to accept a parameter value. Is it possible to use a char array instead? I ask because, to my understanding, instantiating Strings will lead to heap fragmentation. I am setting up a product that will receive many calls to Particle.function and I’m concerned that over time the chip will cough and sputter because of heap fragmentation.

Is it possible to use a char array instead to receive the parameter value? If so, how? Or, does Particle have something up its sleeve allowing the use of String in those functions with no ill effect?

It is not possible to change this behavior, however heap fragmentation should not typically be in an issue in this case. Heap fragmentation occurs when memory blocks have a long lifetime and split larger free spaces into unusably small pieces, divided by unmoveable blocks of memory.

The String object passed to a function handler callback has the lifetime of the duration of the callback, so when you return from the function handler callback, the block of memory will be freed, so there will be no more fragmentation than there would have been if there hadn’t been the temporary heap allocation.

That does make sense that, since it’s such a short period before the String is destroyed and released from heap memory at the end of the function.

Since we’re on the topic of heap. I haven’t seen documentation that clearly states how much memory is on the heap for 3rd gen devices as opposed to the stack. Do you know?

You can declare function handlers thus:
int functionName(const char * command);

Then in the function

int functionName(const char * command)
    char num[16];
    strncpy(num, command, sizeof(num)-1); //make a mutable copy
    if      (strncmp(command, "xyz", 3) == 0)
            return 1;                       // command OK

Depends how ‘purist’ you want to be with String() usage removal but it is as Rick says ‘safe’ in a function call handler.

While you can declare a function handler that way the device OS still creates a String object when the request is received and hands it to the function where the implicit type conversion is pulled to make the parameter fit the bill.

I prefer this function signature for ease of use when I only want to access the parameter as C string (char char*) - which I do prefer over the use of String at any rate :wink:

Unlike stack space the heap space is not pre-reserved. AFAIK when your application starts running everything System.freeMemory() returns can also be used as heap space.

1 Like

Good to know that functions can receive const *char. I think I would prefer this since I am in the habit of using char arrays and this would save me the trouble of converting from String.