2

I have structure with char pointer. I want to allocate static memory to this struct member. How can I do this?

Example:

struct my_data {
    int x;
    bool y;
    char *buf;
 };

How to assign 10 bytes static memory to this char pointer? I know malloc to assign dynamic memory allocation. Is this Ok?

struct my_data data;
char buffer[10];
data.buf = &buffer[0];

PS: I am not allowed to change this struct and use malloc to assign dynamic memory.

1
  • By static you mean that it should persist for the entire run-time of your program? And what you did is legal, but whether or not it's correct depends on your applications needs. Commented Feb 28, 2017 at 8:09

1 Answer 1

3

That will be even simpler (array decays to pointer automatically):

data.buf = buffer;

note that buffer must have an ever-lasting lifetime or you have to make sure that it's not deallocated (i.e. routine where it is declared returns) while you're using it or referencing it.

Allocating from a subroutine and returning will cause underfined behaviour because memory will be deallocated on return.

For instance don't do this (as we often see in questions here):

struct my_data foo()
{
struct my_data data;
char buffer[10];
data.buf = &buffer[0];
return data;
}
int main()
{
   struct my_data d = foo(); // buffer is already gone

Bugs introduced by this kind of UB are nasty because the code seems to work for a while, until the unallocated buffer gets clobbered by another function call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.