I am working on a program to ask a user to enter a word and the number of letters the user wants copied from that word. The program works when I use Compile Online, but when I run the program in Micrsoft Visual Studio, the program freezes after I enter the word I want copied. I ran the debugger and found the error shown below. I take it, from googling, that I am writing past the amount of memory set aside for my array? Should I use malloc to fix that? Posted below are the errors and the code (link to original stackoverflow thread.
Exception thrown at 0x0FFB0BA0 (ucrtbased.dll) in lab1113problem7.exe: 0xC0000005: Access violation writing location 0x00B80000.
Unhandled exception at 0xFEFEFEFE in lab1113problem7.exe: 0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003).
The program '[7196] lab1113problem7.exe' has exited with code 0 (0x0).
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *copywords(char *dest, const char *source, size_t n);
int main(void) {
char words[50];
char newwords[50];
int num;
for (;;) {
printf("Type a word, or type 'quit' to quit: ");
if (scanf("%49s", words) != 1) {
printf("Invalid input!\n");
return 0;
}
if (!strcmp(words, "quit")) {
printf("Good bye!\n");
return 0;
}
printf("Type the # of chars to copy: ");
if (scanf("%d", &num) != 1) {
printf("Invalid input!\n");
return 0;
}
copywords(newwords, words, num);
printf("The word was %s\n", words);
printf("and the copied word is %s\n", newwords);
}
}
char *copywords(char *dest, const char *source, size_t n) {
size_t i;
for (i = 0; i < n && source[i] != '\0'; i++) {
dest[i] = source[i];
}
dest[i] = '\0';
return dest;
}