0

Why does the call to strcpy crashes in the following code? Also why is it crashing in CodeBlocks, but not in VS?

#define MAX 500
char* GetUserAnswer(char* detail)
{
    char answer[MAX];
    printf("Provide %s:", detail);
    scanf("%s", answer);

    return answer;
}

void PrelucreazaSablon(FILE* generatedFile)
{
    char answer[MAX];
    strcpy(answer, GetUserAnswer("name"));
    fputs(answer, generatedFile);
}
IMSoP
  • 89,526
  • 13
  • 117
  • 169
Gabriela
  • 29
  • 5
  • You have undefined behavior because the returned pointer from `GetUserAnswer` is out of scope when you try to access it. – SuperStormer May 09 '21 at 21:52
  • You return a dangling pointer, since the local array `answer` is already destroyed when it arrives to `strcpy`. This causes "undefined behavior", which may manifest as a crash, but doesn't have to. – HolyBlackCat May 09 '21 at 21:52

0 Answers0