-1

I'm just doing some practice code but I can't figure out this stubborn Thread 1:

signal SIGABRT error.

int main(){
    char diet[] = "vegan";

    printf("Because of health concerns, my diet is now %s.\n", diet);

    strcpy(diet, "whatever");

    printf("Before the health concerns, my diet was %s.\n", diet);


    return 0;
}
Vishnu T S
  • 3,476
  • 2
  • 23
  • 39
  • 2
    You are trying to use `strcpy` to copy 9 characters (including null terminator) to a space that can only hold 6. – Galen Dec 19 '17 at 03:43

2 Answers2

1

strlen("whatever") > strlen("vegan") = undefined behavior.

Why do you think you need to copy the strings around. You could just do:

int main(){
    char *diet = "vegan";
    printf("Because of health concerns, my diet is now %s.\n", diet);
    diet = "whatever";
    printf("Before the health concerns, my diet was %s.\n", diet);
    return 0;
}
John3136
  • 28,809
  • 4
  • 51
  • 69
1

You need to allocate more memory to solve this; you cannot store 9 bytes in 6 bytes space — that causes an error.

Solution

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

char *create(const char *src) { 
   char *ret = calloc(sizeof(char*) , strlen(src) + 1);
   strcpy(ret , src);
   return ret;
}

int main(){
   char *diet = create("Vegan");
   printf("Because of health concerns, my diet is now %s.\n", diet);
   free(diet); // always free it after using it or before changing it

   diet = create("whatever");
   printf("Before the health concerns, my diet was %s.\n", diet);
   free(diet);

   return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
antonyjr
  • 61
  • 1
  • 5