Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C String Length using null

Tags:

c

string

I know the C language has dynamic length strings whereby it uses the special character null (represented as 0) to terminate a string - rather than maintaining the length.
I have this simple C code that creates a string with the null character in the fifth index:

#include <stdio.h>
#include <stdlib.h>
int main () {   
  char * s= "sdfsd\0sfdfsd";
  printf("%s",s);
  s[5]='3';
  printf("%s",s);
  return 0;
}

Thus, a print of the string will only output up to the fifth index. Then the code changes the character at the fifth index to a '3'. Given my understanding, I assumed it would print the full string with the 3 instead of the null, as such: sdfsdsdfsd3sfdfsd

but instead it outputs: sdfsdsdfsd

Can someone explain this?

like image 769
Favn Hghksd Avatar asked May 16 '26 21:05

Favn Hghksd


2 Answers

This program exhibits undefined behavior because you modify a read-only string literal. char* s = "..." makes s point to constant memory; C++ actually disallows pointing non-const char* to string literals, but in C it's still possible, and we have to be careful (see this SO answer for more details and a C99 standards quote)

Change the assignment line to:

char s[] = "sdfsd\0sfdfsd";

Which creates an array on the stack and copies the string to it, as an initializer. In this case modifying s[5] is valid and you get the result you expect.

like image 170
Eli Bendersky Avatar answered May 20 '26 00:05

Eli Bendersky


String literals can not be changed because the compiler put the string literals into a read-only data-section (but this might vary by underlying platform). The effect of attempting to modify a string literal is undefined.

In your code:

char * s= "sdfsd\0sfdfsd"

Here, s is char pointer pointing to a string "sdfsd\0sfdfsd" stored in read-only memory, making it immutable.

Here you are trying to modify the content of read-only memory:

s[5]='3';

which leads to undefined behavior.

Instead, you can use char[]:

#include <stdio.h>

int main () {
  char a[] = "sdfsd\0sfdfsd";
  char * s = a;
  printf("%s",s);
  s[5]='3';
  printf("%s\n",s);
  return 0;
}
like image 26
H.S. Avatar answered May 20 '26 02:05

H.S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!