Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Char Pointer Crash

Let's say that a function which returns a fixed ‘random text’ string is written like

char *Function1()
{ 
return “Some text”;
}

then the program could crash if it accidentally tried to alter the value doing

Function1()[1]=’a’;

What are the square brackets after the function call attempting to do that would make the program crash? If you're familiar with this, any explanation would be greatly appreciated!

like image 761
THE DOCTOR Avatar asked Nov 30 '22 09:11

THE DOCTOR


2 Answers

The string you're returning in the function is usually stored in a read-only part of your process. Attempting to modify it will cause an access violation. (EDIT: Strictly speaking, it is undefined behavior, and in some systems it will cause an access violation. Thanks, John).

This is the case usually because the string itself is hardcoded along with the code of your application. When loading, pointers are stablished to point to those read-only sections of your process that hold literal strings. In fact, whenever you write some string in C, it is treated as a const char* (a pointer to const memory).

like image 69
Diego Sevilla Avatar answered Dec 05 '22 06:12

Diego Sevilla


The signature of that function should really be constchar* Function();.

like image 26
Nikolai Fetissov Avatar answered Dec 05 '22 05:12

Nikolai Fetissov