Pointers and strings and string constants, using GDB to get information in illegal memory

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.