Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining pointer to a string constant

short var = *((unsigned short*)&"BM");

"BM" must be located somewhere in read-only memory area then why can't I obtain a pointer to it? (It compiles but it says invalid memory area (clang compiler))

like image 374
Imobilis Avatar asked Apr 16 '15 11:04

Imobilis


People also ask

How do you declare a pointer to a constant string?

A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.

Is string a constant pointer?

The type of a narrow string literal is an array of char , and the type of a wide string literal is an array of wchar_t . However, string literals (of both types) are notionally constant and should consequently be protected by const qualification.

What is the difference between pointer to constant and constant pointer?

In the pointers to constant, the data pointed by the pointer is constant and cannot be changed. Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable).

Can we modify string literal in C?

The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.


1 Answers

C does not permit taking the address of a literal:

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

-- C99 6.5.3.2/1

Literals do not fall into any of the permitted categories of operands. This is a formal constraint of the language -- conforming implementations are not required to accept code that violates it, and are required to produce diagnostics describing violations. C does not define the behavior of code that violates a constraint.

You can achieve something similar to what you seem to want like so:

union short_str {
    char str[3];
    int16_t sh;
} u = { "BM" };
short var = u.sh;

Among other things, this avoids the risk of dereferencing a pointer to misaligned storage. C will align the storage for variable u so that all members are aligned on an appropriate boundary. This avoids a possible pitfall with any approach along the lines you originally attempted.

like image 130
John Bollinger Avatar answered Sep 28 '22 22:09

John Bollinger