0

I usually make myself a struct and I allocate memory for the struct and sometimes for buffers inside the struct. Like so:

typedef struct A
{
  char *buffer;
  int size;
} A;

Then when I malloc for the struct I do this. (I learned not to cast the malloc return here on SO.)

X

A *a = malloc(sizeof(a));
a->buffer = malloc(10*sizeof(a->buffer));

What is the difference between X and Y this?

Y

 A *a = malloc(sizeof(*a));
 a->buffer = malloc(10*sizeof(a->buffer));

They seem to be doing the same thing.

Mike John
  • 818
  • 4
  • 11
  • 29
  • I'm supposing your `buffer` pointer points to an arbitrary amount of data? It's not clear from your code snippet. In that case, `a->buffer = malloc(sizeof(a->buffer)` is wrong since it will always only allocate 4 bytes or 8 bytes depending upon whether you are on a 32-bit or 64 bit machine. – lurker Dec 07 '13 at 13:07
  • 1
    The difference is that `sizeof(a*)` is a syntax error whereas `sizeof(a)` is more subtly wrong. – Pascal Cuoq Dec 07 '13 at 13:09
  • Why do you want to allocate 10 times the size of a buffer pointer for our buffer? – lurker Dec 07 '13 at 13:11
  • I want to allocate space for 10 characters. – Mike John Dec 07 '13 at 13:13

2 Answers2

6

Neither is correct, the second one doesn't even compile.

You want either of these:

A * a = malloc(sizeof(A));    // repeat the type

// or:

A * a = malloc(sizeof *a);    // be smart

Then:

a->size = 213;
a->buffer = malloc(a->size);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • `a->buffer = malloc(a->size);` Will the compiler know to do `size * character size`? – Mike John Dec 07 '13 at 13:12
  • 1
    @MikeJohn: `sizeof(char)` is one, by definition. Generally, though, you'll have to multiply by the size of the type, indeed. – Kerrek SB Dec 07 '13 at 13:13
  • Although I added `10` * sizeof... in an edit why do you say the second doesn't compile? – Mike John Dec 07 '13 at 13:18
  • Anyway, what I learned from you is that it should be with the pointer. `malloc(sizeof *a);` Thanks. – Mike John Dec 07 '13 at 13:20
  • @MikeJohn: The question was edited, so that's not a fair use of time. It originally said `sizeof(a*)`, which isn't valid C. Never mind. – Kerrek SB Dec 07 '13 at 13:27
  • @MikeJohn: Well, I would phrase this as "Use `sizeof` with an *expression*, not a *type*." The asterisk denoted dereference in this case. – Kerrek SB Dec 07 '13 at 13:28
0

you should typecast it (A *) because calloc or malloc return void *.

A *a=(a*)malloc(sizeof(A));

suppose you want to allocate memory for buffer for 10 characters

a->buffer=(char *)malloc(sizeof(char)*10);
InvisibleWolf
  • 917
  • 1
  • 9
  • 22