Reputation: 31
I'm learning C and recently I was trying some tutorials from youtube, and I was running this code, but it doesnt work I don't know why... when i run it on Terminal, gives an error "Abort trap: 6"
I was following this tutorial : https://youtu.be/7F-Q2oVBYKk?list=PL6gx4Cwl9DGAKIXv8Yr6nhGJ9Vlcjyymq
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char name[15] = "John Snow";
printf("My name is %s\n", name);
name[2] = 'z';
printf("My name is %s\n", name);
char food[] ="pizza";
printf("The best food is %s \n", food);
strcpy(food, "bacon");
printf("The best food is %s \n", food);
return 0;
}
Upvotes: 3
Views: 18027
Reputation: 129
The error means you are writing to memory you don't own. Will likely happen if you try to copy a string longer than the one you specified for food ('pizza'). In this case it could be cos you are copying the string into memory location assigned to a string constant.
try this instead:-
char *food = malloc(sizeof(char)*6);
strcpy(food, "pizza");
printf("The best food is %s \n", food);
strcpy(food, "bacon");`
printf("The best food is %s \n", food);
Upvotes: 4