As written in title, the exception "project has triggered a breakpoint" is thrown. I have searched for an answer in the forum, but I have seen that this exception is thrown in a variety of cases, and I couldn't indicate a solution to this exception in my program. The interesting thing is that sometimes the program runs as it should, without any exceptions, and sometimes it just does not. I think it relates to a memory issue, but I can't find something wrong. Thus, I will be glad to get your help.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* str;
char character;
int i = 0;
str = (char*)malloc(sizeof(char)*1 + 1 ); //+1 for the '\0'
if (str == NULL) return 1;
printf("Please enter a character: ");
scanf_s(" %c", &character);
while (character != 'X')
{
str[i] = character;
i++;
str[i] = '\0';
realloc(str, sizeof(char)*1 + strlen(str) + 1);//+1 for the '\0'
printf("Please enter a character: ");
scanf_s(" %c", &character);
}
str[i] = '\0';
printf("%d\n", strlen(str)); //Debug.
puts(str); //Pring string.
free(str);
return 0;
}
If my question is not clear enough, write it in comments and I will be glad to clarify the question.
Thank you very much beforehand!