juantorena
juantorena

Reputation: 71

How much memory allocate each line of code?

char *str1 = "warning";
char str[] = "warning";
char str3[] = {'c', 'a', 't'};
char *str4[] = {"warning", "program"};
char *str5[2][20] = {"waring", "program"};

In my opinion second line of code should allocate 8 bytes of memory, but correct answer is 16bytes. Why?

Upvotes: 1

Views: 841

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

It depends on what you mean by "allocate"; none of these methods do any dynamic heap-based allocation in the sense of malloc().

If you mean, "how much space is reserved on the stack", then the answer for the second line could well be 8, but it depends on your platform and compiler. The compiler may decide to align all stack variables to 16-byte boundaries, for instance.

Of course, at least 8 bytes of static program space will also be required to store the string literal "warning" in order to initialise str. The compiler may be intelligent enough to spot that you're using the same string literal in multiple places, or it may not. Again, it depends.

About the only thing that doesn't depend on the compiler is the fact that sizeof(str) should always be 8.

Upvotes: 5

Lie Ryan
Lie Ryan

Reputation: 64855

what do you mean?

$ cat mem.c 
#include <stdio.h>

int main() {
    char str[] = "warning";
    printf("%li\n", sizeof(str));
}

$ gcc mem.c 
$ ./a.out 
8

Upvotes: 0

Related Questions