String literals are stored as read-only (const
), and any attempt to modify the pointer returned will result in a SEGFAULT (crash) in most current computing environments.
Obvserving the following assembly output from GCC:
.file "tst.c"
.text
.section .rodata
.LC0:
.string "Hello World."
.text
.globl Hi
.type Hi, @function
Hi:
You can see string literal referred to by label .LC0 is defined within section '.rodata' meaning ready-only data.
Therefore Hi()
should have a return type of const char*
to avert the possibility of such faulty access occurring.
const char* Hi (void) { return("Hello World."); } char *oopsHi(void) { return ("Hello World."); }
char* Hi (void)- const char* Hi (void)
- {
return("Hello World.");}- return("Hello World.");
- }
- char *oopsHi(void)
- {
- return ("Hello World.");
- }
// TODO: Replace examples and use TDD development by writing your own tests. The code provided here is just a how-to example. #include <criterion/criterion.h> // replace with the actual method being tested const char* Hi (); Test(the_multiply_function, should_pass_all_the_tests_provided) { cr_assert_eq(Hi(""), "Hello World."); #if 0 // if'd out, reenable to observe crash char oopsHi(); char *p = oopsHi(); *p = 'X'; #endif }
- // TODO: Replace examples and use TDD development by writing your own tests. The code provided here is just a how-to example.
- #include <criterion/criterion.h>
- // replace with the actual method being tested
char* Hi ();- const char* Hi ();
- Test(the_multiply_function, should_pass_all_the_tests_provided) {
- cr_assert_eq(Hi(""), "Hello World.");
- #if 0 // if'd out, reenable to observe crash
- char oopsHi();
- char *p = oopsHi();
- *p = 'X';
- #endif
- }