0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{   
    int n = 5;
    char str1[n];
    char *str2;
    char str3[] = "World!";

    // dynamically allocate memory for string 2 
    str2 = malloc(sizeof(char) * n);
    
    // Copy strings into string 1 and 2
    strcpy(str2, "Hello");
    strcpy(str1, "Oi! ");

    // print memory locations
    printf("%s -> %p\n", str1, &str1);
    printf("%s -> %p\n", str2, &str2);
    printf("%s -> %p\n", str3, &str3);
    return 0;
}

So why is str1 and str3 lower addresses than str2 when printing memory locations? I thought higher addresses were for the stack and lower addresses for the heap. So if it is because of the reference variables address than why is it higher than str1, when str1 was declared first?

1 Answer 1

0

The addresses are allocated randomly, so the address of str3 could also be less than str1.

Hope this helps. If it does, then please check the tickmark.

2
  • For sure, I am still not clear why str2 is always at higher address than both the others. Appreciate the help though. Jan 24, 2021 at 14:23
  • I would also recommend that you use a free(str2); statement before return as your programs leaks memory each time it is run
    – Vsjain
    Jan 24, 2021 at 15:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .