Search code examples
csegmentation-faultcoredump

Segmentation fault (core dumped) copying form array to string


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

int main()
{

char str[255] = "Hello;thisnewwolrd";

int i =0;
while(str[i] != ';')
{
   i++;
}
i++;

 char *name = NULL;
 while(str[i] != NULL)
{

  name[i] = str[i];
  i++;
    printf("%c \r\n",name[i]);
 }

}

the expected output is thisnewwolrd but i am getting error of core dumped canany one have reason why and how to over come this


Solution

  • This should work:

    int main()
    {
        char str[255] = "Hello;thisnewwolrd";
        char *ptr = strchr(str, ';') + 1;
    
        char name[255];
        strcpy( name, ptr);
    
        printf("%s \r\n", name);
    }
    

    You don't have to reinvent the wheel, and are much better off using standard library functions for string manipulation.