+ 1

Help me with a pointer!

I tried this code: char *str; scanf("%s", str); printf("%s", str); I inserted: Hello but I got no output So I thought maybe my pointer is "empty" then I tried: char *str = "HelloWorld"; scanf("%s", str); printf("%s", str); I inserted: Hello Still got no output So I allocate 15 bytes to try to understand char *str = malloc(15); scanf("%s", str); printf("%s", str); free(str); I inserted: Hello This time it worked Can someone explain why assign a string to the pointer did not worked? Thanks

19th Jan 2022, 8:35 PM
Mario Paes
Mario Paes - avatar
5 Respostas
+ 4
In the first case, you declare a pointer to char, but nothing that it points to. It will have a random address, as soon as you write to it, it will probably crash (SIGSEGV). In the second case, your pointer points to a string literal. String literals reside in read-only memory. As soon as you write to it, your program will crash. In the third case you allocate memory on the heap and point your pointer to it. That is correct. An alternative would be a stack memory region using a fix-sized char array, for example: char buf[15];
19th Jan 2022, 8:45 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 4
Mario Paes and Jonas There is one mistake: the Operating System or any programming language doesn't have access to write the ROM (Read Only Memory). Thus, a programming language can't write memory addresses in here to store some values (string literal or constants). ROM is accessed only by the BIOS (read and write). Instead, RAM is split by the programming language, especially C, in multiple zones: stack, heap and maybe more. A string literal or a constant is a variable that cannot be change at runtime.
19th Jan 2022, 9:58 PM
Romeo Cojocaru
Romeo Cojocaru - avatar
+ 2
Thank you! Jonas
19th Jan 2022, 8:49 PM
Mario Paes
Mario Paes - avatar
+ 2
Thanks Romeo Cojocaru for the advice!
19th Jan 2022, 10:02 PM
Mario Paes
Mario Paes - avatar
+ 2
Romeo Cojocaru Thank you for the clarification. I was a little imprecise about the .rodata segment calling it "read-only memory". On purpose though, as I did not want to go into too much detail :) Mario Paes you're most welcome :)
19th Jan 2022, 11:57 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar