user9022429
user9022429

Reputation: 11

how can i correct this error? segmentation fault (core dumped)

I'm new to coding and I was doing an exercise and this error came up when compiling "Segmentation fault (core dumped) and I have no idea how to correct it and I've looked up the error but I don't really understand it

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

int main()
{


char Kid1[12];

char Kid2[] = "Maddie";

char Kid3[7] = "Andrew";

char Hero1 = "Batman";

char Hero2[34] = "Spiderman";

char Hero3[25];

Kid1[0] = 'K';
Kid1[1] = 'a';
Kid1[2] = 't';
Kid1[3] = 'i';
Kid1[4] = 'e';
Kid1[5] = '\0';

strcpy(Hero3, "The incredible Hulk");

printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
printf("%s\'s favorite hero is %s.\n", Kid2, Hero2);
printf("%s\'s favorite hero is %s.\n", Kid3, Hero3);

return 0;

}

Upvotes: 0

Views: 668

Answers (2)

bekici
bekici

Reputation: 84

I agree:

Change char Hero1 = "Batman"; to char *Hero1 = "Batman";. Pay attention to compiler messages.

But I think more accurately const char *Hero1 = "Batman";

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222302

Read the compiler warnings. When the source code in the question is compiled, the compiler will warn that the statement char Hero1 = "Batman" attempts to convert a char * or char [7] to char. It attempts to assign a string to a char.

When you ignore the warning and run the program, the address of the string will be converted in some way to a char.

A good compiler will also warn that printf("%s\'s favorite hero is %s.\n", Kid1, Hero1); passes a char (Hero1) where printf is expected a string (pointer to a char) for %s. Since the char you are passing does not contain a proper pointer, printf gets a bad address, and this causes the segment fault.

Change char Hero1 = "Batman"; to char *Hero1 = "Batman";. Pay attention to compiler messages.

Upvotes: 4

Related Questions