Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

426
Vistas
When to allocate memory to char *

I am bit confused when to allocate memory to a char * and when to point it to a const string.

Yes, I understand that if I wish to modify the string, I need to allocate it memory.

But in cases when I don't wish to modify the string to which I point and just need to pass the value should I just do the below? What are the disadvantages in the below steps as compared to allocating memory with malloc?

char *str = NULL;

str = "This is a test";

str = "Now I am pointing here";
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Let's try again your example with the -Wwrite-strings compiler warning flag, you will see a warning:

warning: initialization discards 'const' qualifier from pointer target type

This is because the type of "This is a test" is const char *, not char *. So you are losing the constness information when you assign the literal address to the pointer.

For historical reasons, compilers will allow you to store string literals which are constants in non-const variables.

This is, however, a bad behavior and I suggest you to use -Wwrite-strings all the time.

If you want to prove it for yourself, try to modify the string:

char *str = "foo";
str[0] = 'a';

This program behavior is undefined but you may see a segmentation fault on many systems. Running this example with Valgrind, you will see the following:

Process terminating with default action of signal 11 (SIGSEGV)
  Bad permissions for mapped region at address 0x4005E4

The problem is that the binary generated by your compiler will store the string literals in a memory location which is read-only. By trying to write in it you cause a segmentation fault.

What is important to understand is that you are dealing here with two different systems:

  1. The C typing system which is something to help you to write correct code and can be easily "muted" (by casting, etc.)

  2. The Kernel memory page permissions which are here to protect your system and which shall always be honored.

Again, for historical reasons, this is a point where 1. and 2. do not agree. Or to be more clear, 1. is much more permissive than 2. (resulting in your program being killed by the kernel).

So don't be fooled by the compiler, the string literals you are declaring are really constant and you cannot do anything about it!

Considering your pointer str read and write is OK. However, to write correct code, it should be a const char * and not a char *. With the following change, your example is a valid piece of C:

const char *str = "some string";
str = "some other string";

(const char * pointer to a const string)

In this case, the compiler does not emit any warning. What you write and what will be in memory once the code is executed will match.

Note: A const pointer to a const string being const char *const:

const char *const str = "foo";

The rule of thumb is: always be as constant as possible.

If you need to modify the string, use dynamic allocation (malloc() or better, some higher level string manipulation function such as strdup, etc. from the libc), if you don't need to, use a string literal.

over 4 years ago · Santiago Trujillo Denunciar

0

If you know that str will always be read-only, why not declare it as such?

char const * str = NULL;
/* OR */
const char * str = NULL;

Well, actually there is one reason why this may be difficult - when you are passing the string to a read-only function that does not declare itself as such. Suppose you are using an external library that declares this function:

int countLettersInString(char c, char * str);
/* returns the number of times `c` occurs in `str`, or -1 if `str` is NULL. */

This function is well-documented and you know that it will not attempt to change the string str - but if you call it with a constant string, your compiler might give you a warning! You know there is nothing dangerous about it, but your compiler does not.

Why? Because as far as the compiler is concerned, maybe this function does try to modify the contents of the string, which would cause your program to crash. Maybe you rely very heavily on this library and there are lots of functions that all behave like this. Then maybe it's easier not to declare the string as const in the first place - but then it's all up to you to make sure you don't try to modify it.

On the other hand, if you are the one writing the countLettersInString function, then simply make sure the compiler knows you won't modify the string by declaring it with const:

int countLettersInString(char c, char const * str);

That way it will accept both constant and non-constant strings without issue.

over 4 years ago · Santiago Trujillo Denunciar

0

One disadvantage of using string-literals is that they have length restrictions. So you should keep in mind from the document ISO/IEC:9899 (emphasis mine)

5.2.4.1 Translation limits

1 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:

[...]

— 4095 characters in a character string literal or wide string literal (after concatenation)

So If your constant text exceeds this count (What some times throughout may be possible, especially if you write a dynamic webserver in C) you are forbidden to use the string literal approach if you want to stay system independent.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda