0

why is my code producing SIGSEGV in the indicated line? I want to change the first character of my string to 'k' (lowercase)

#include <stdio.h>
    #include <stdlib.h>
    #include<string.h>
    struct node
    {
        int data;
        struct node* next;
    };
    void fun1(char** head)
    {
        printf("FUN2---%s",*head);
    //this line produces a segmentation fault
       **head='k';

    }
    void fun(char** head)
    {
      printf("FUN---HEAD:%s\n",*head);
        fun1(head);
    }

    int main()
    {
        char *ptr="KEWIN";
        printf("PTR:%p\n",ptr);
        fun(&ptr);

        printf("%s",ptr);
        return 0;
    }
  • 5
    You are trying to change the first character of a *string literal*. – Weather Vane Jun 18 '17 at 08:43
  • ... or of [this one](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) which has been protected. – Weather Vane Jun 18 '17 at 09:01

1 Answers1

1

You are trying to change a string literal which, depending on the compiler implementation, may or may not be placed in the read only data segment of your compiled program. If it is placed in the read only data segment any attempt to write there will result in a segfault. Making your name a char name[] rather than char * name will place the string on the stack and you'll be able to write to it there. Also, passing a char ** to your functions adds an unnecessary level of indirection. See this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
    int data;
    struct node* next;
};
void fun1(char * head)
{
    printf("FUN2---%s\n", head);
    // no seg fault anymore
   *head='k';

}
void fun(char * head)
{
  printf("FUN---HEAD:%s\n",head);
    fun1(head);
}

int main()
{
    char name[] = "KEWIN";
    printf("PTR:%p\n",name);
    fun(name);

    printf("%s",name);
    return 0;
}
Vlad Dinev
  • 432
  • 2
  • 9