简体   繁体   中英

Allocating memory for structs, 2 different ways?

I am new in C, but not new in programming. Is there a difference between the 2 sets of codes ? If there is not, is there a convention on which one to prefer ? Is there a performance difference ?

typedef struct
{
    int x;
    int y;
} something_t;

-

something_t* s;
s = malloc(sizeof(int)*2);
s->x = 1;
s->y = 1;

or

something_t* s;
s->x = 1;
s->y = 1;

To my understanding, the first version should be

something_t* s;
s = malloc(sizeof(something_t));
s->x = 1;
s->y = 1;

instead of manually fiddling with the size of individual members; the second versions performs no allocation at all and accesses uninitialized memory.

something_t* s;

does not allocate any memory for your structure, it only allocates a pointer (to a random memory area). It is very likely it will trigger a segmentation fault when you try to read/write to it.

The good way to allocate your memory is

something_t* s;
s = malloc(sizeof(something_t));

or the one-liner

something_t* s = malloc(sizeof(something_t));

Don't forget to use free(s); when you're done with it.

If you want stack-allocation, you can use :

something_t s;
s.x = 2;
s.y = 2;

The good way to do it is

something_t *something;
something = malloc(sizeof(*something));
if (something == NULL)
    please_do_not_use_something_perhaps_return_NULL_or_quit();
something->x = 2;
something->y = 2;

This way, you ensure the size is right and the code is more maintainable. And you also prevent a disaster by checking that malloc() didn't return NULL giving you chance to do something about it. Assuming no-errors is wrong all the time, in this because you never know when the system will run out of RAM.

Your second example doesn't work, this

something_t *something;
something->x = 2;
something->y = 2;

Invokes Undefined Behavior , one of the possible outcomes is that it " Works ". So you might think that it worked because of undefined behavior, but the truth is, it's wrong.

In this case something doesn't point to valid memory, so you don't know for sure what the value of something is and it can be anything, thus the behavior of such program is unpredictable.

Also, read why you should avoid _t as a suffix for type names .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM