-2

What's the difference between char str[10] and char *str = (char *) malloc(10)? As I understand, don't both of them allocate 10 bytes for an array of chars?

Bluefire
  • 13,519
  • 24
  • 74
  • 118
  • If `char str[10]` is used outside a function, it is a global variable. The memory is allocated by the compiler and becomes (probably) part of your binary (as it is initialized). If `char str[10]` is used inside a function, it is allocated on _stack_ each time the function is entered (and released on return). `char *str = (char *) malloc(10)` allocates the memory in the _heap_. You are responsible to release it (using `free()`). Otherwise it is called a leak, once you re-assign `str` with another address (i.e. the allocated memory gets "lost" until end of program). – Scheff's Cat Nov 04 '17 at 17:28
  • 2
    If you didn't find it in your C book, throw it away and buy a good one... ;-) – Scheff's Cat Nov 04 '17 at 17:32

2 Answers2

1
  1. char str[10];

Global (static) scope - allocated in the .data or .bss segments (depending on the initialisation. Cannot be freed before program termination.

Local (automatic) scope - usually (most implementations but C standard does not defie anything like the "stack") allocated on the stack. Automatically freed when program leaves the scope.

2.

char *str = malloc(10);

Allocated on heap. Needs to be freed by the program using the free function

0___________
  • 60,014
  • 4
  • 34
  • 74
-1

char str[10] allocate memory on stack. char *str = (char *) malloc(10) allocate memory on heap. Stack and Heap stored in the computer's RAM. More information about stack and heap.

svm
  • 392
  • 3
  • 9