Why is my char* writable and sometimes read only in C++

后端 未结 4 1518
天涯浪人
天涯浪人 2020-12-21 09:28

I have had really big problems understand the char* lately. Let\'s say I made a recursive function to revert a char* but depending on how I initial

4条回答
  •  眼角桃花
    2020-12-21 10:11

    The key is that some of these pointers are pointing at allocated memory (which is read/write) and some of them are pointing at string constants. String constants are stored in a different location than the allocated memory, and can't be changed. Well most of the time. Often vulnerabilities in systems are the result of code or constants being changed, but that is another story.

    In any case, the key is the use of the new keyword, this is allocating space in read/write memory and thus you can change that memory.

    This statement is wrong

    char * bob = new char[6];
    bob = "hello\0";
    

    because you are changing the pointer not copying the data. What you want is this:

    char * bob = new char[6];
    strcpy(bob,"hello");
    

    or

    strncpy(bob,"hello",6);
    

    You don't need the nul here because a string constant "hello" will have the null placed by the compiler.

提交回复
热议问题