-3

In C, is there a difference between

struct Foo foo;
struct Foo* fooPtr = &foo;

and

struct Foo* fooPtr = (struct Foo*) malloc(sizeof(struct Foo));

5 Answers5

1

Of course there is.

It depends on where you allocate the foo variable - it may be in the (statically allocated) data segment or just on the stack. In the first case, it will never go away, and in the second case, it might go away too soon, depending on what you do with the pointer.

OTOH, if you malloc(), the data is put onto the heap, and it will stay until you free() it. This allows you to be flexible with your memory.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

Yes There is a difference.

Because of dynamic memory allocation in the second case, it will be allocated in heap section of memory and you need to free it explicitly, How ever in first case you do not need to take care of that as it is allocated in the stack section of Memory.

Sudipta Kumar Sahoo
  • 1,049
  • 8
  • 16
0

malloc-ed memory must be free-ed, stack and global memory doesn't need to be. malloc-ed memory lives until free-ed, stack memory goes away when the function returns. malloc-ed memory can be dynamically sized at runtime, global memory cannot (and while in C99 and higher, stack memory can be dynamically sized, there are limits as far as stability and performance goes).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Sure there is. It has to do with how long the memory for that variable is alive.

int * bad_code() {
    int x;
    return &x;
}

int good_code() {
    int *x = malloc(sizeof(int));
    return x;
}

Using the memory referred to by bad_code() is not allowed. But you can continue to use the memory referred to by good_code().

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

Yes the first is stored either on the stack if declared as a function local or in data memory if declared as a file global. So that your pointer is pointing to this part of memory.

In the latter case, malloc allocates memory on the heap and the pointer points to memory on the heap. This must be freed as stated by others.

cdcdcd
  • 547
  • 1
  • 5
  • 15