Routine 1
#include <stdio.h>int main (void) { char *s= "Hello"; printf ("%s\n", s); s[0]= "H" //Because the string "hello" pointed to by the S pointer is a string constant, it cannot be changed by the pointer, so there is a fragment error in printf ("%s\n", s); return 0;}
Routine 2
#include <stdio.h> #include <string.h> #include <stdlib.h>int main (void) { char *s = (char *) malloc (6*sizeof (char)); strcpy (S, "Hello"); printf ("%s\n", s); S[0] = ' H '; Because S is allocated dynamic memory, changes can be changed by the S-pointer printf ("%s\n", s); return 0;}
Routine 3
The starting position of the string is not specified, but it must be used as a trailing identifier
int main (void) { char *s= "Hello"; printf ("%s\n", s); Print out Hello printf ("%s\n", &s[1]); Print out Ello printf ("%s\n", &s[1]); Print out Llo //... printf ("%s\n", &s[4]); Print out o return 0;}
Suppose that routine 3 is named String.c
Compile the program with the command gcc-g-o string string
Then use GDB/string to debug the program.
Break Main
Run
Next
Next
Print S
Display result $ = 0x40061c "Hello"
Print s+1
Display result = 0x40061d "Ello"
Print S[1]
Showing results $3= 0x40061d ' e '
Note the difference between print s+1 and print s[1], where print s+1 is equivalent to print &s[1]
The above 3 print commands are access to a valid area of memory in a string program
Print s+10
The result of the display may be $4 = 0x400626 "\003;
This print statement actually accesses the illegal memory area in string (out-of-bounds access), but access through GDB can also be used to obtain relevant information. Sometimes it is possible to get some useful information by using GDB to obtain a piece of memory that has been used illegally but may have some useful information.
Pointers and strings and string constants, using GDB to get information in illegal memory