When trying change symbol in char* string got an Segmentation fault error

Viewed 32

When I execute the next code it runs fine

// Example program
#include <string.h>
#include <stdio.h>

int main()
{
  char *dbString = strdup("172.0.0.1:5000");
  char *port = strchr(dbString, ':');
  printf("port = %s\n", port);
  if (port)
    *port++ = '\0';
  printf("port = %s\n", port);
  return 0;
}

But if I execute the next code I got an error.

// Example program
#include <string.h>
#include <stdio.h>

int main()
{
  char *port = (char*) ":5000";
  printf("port = %s\n", port);
  if (port)
    *port++ = '\0';
  printf("port = %s\n", port);
  return 0;
}

Could you explain to me the reason for the error?

1 Answers

In your second example, ":5000" is a string literal. The compiler places the string literal in a readonly memory section. You are trying to change that string which is ilegal.

Related