Jonas Frey
Jonas Frey

Reputation: 97

setting a character via index on a malloc char pointer not working

  char * s_string = malloc(0);
  s_string = "1234567";
  // s_string[7] = 'a'; // why not working ?...
  s_string = "123456a"; // but this works...
  printf("s_string = %s\n", s_string);
  s_string = "123412341234123412341234"; // does this do a realloc ?

when i try to set a single char i get a 145382 segmentation fault (core dumped) but when i set the whole string with my char at the index, it works... also , does setting a value of a char pointer with a literal value do a realloc on the char pointer ?
the code should explain my question...

Upvotes: 0

Views: 103

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

This code snippet

char * s_string = malloc(0);
s_string = "1234567";

produces a memory leak provided that the system indeed allocated memory instead of returning NULL.

That is at first memory was allocated and its address was assigned to the pointer s_string and then the pointer was reassigned with the address of the first character of the string literal "1234567". So the address of the allocated memory was lost.

In this code snippet

s_string = "1234567";
s_string[7] = 'a'; // why not working ?.

you are trying to change the string literal pointed to by the pointer s_string. Any attempt to change a string literal results in undefined behavior.

In this code snippet

s_string = "123456a"; // but this works...
printf("s_string = %s\n", s_string);

the pointer s_string was just reassigned with the address of another string literal.

In this statement

s_string = "123412341234123412341234"; // does this do a realloc ?

neither reallocation occurs. Again the pointer is reassigned with the address of another string literal and nothing more.

You may change the value stored in the pointer s_string because it is not a constant pointer.

For example if the pointer was declared like

char * const s_string = "1234567";

then the compiler would issue an error message for this assignment statement

s_string = "123456a";

Upvotes: 1

Related Questions