I was trying to write out some of the implementations of the string functions available in C. My code is:
#include <stdio.h>
#include <stdlib.h>
char *mystrcpy(char *s1, char *s2)
{
while(*s1++ = *s2++);
return s1;
}
int mystrlen(char *s)
{
int len = 0;
while(*s != '\0')
{
len++;
}
return len;
}
int main(void)
{
char arr = "Hi";
char arr1[10];
char arr2[] = "Hello";
int length;
mystrcpy(arr1, arr2);
printf("%s", arr1);
length = mystrlen(arr);
printf("%d", length);
return 0;
}
mystrcpy works fine, but the other method mystrlen does no execute. What could be the error? The following is the program termination note:
Process terminated with status -1073741510 (0 minutes, 4 seconds)
Also, there are few warnings related to casts. Is there any place in the code where I should be using any cast?
First, your
mystrlenhas an infinite loop.Fixed code:
Also added
constsince you never change the data referred to by*sSecond, the assignment:
char arr="Hi";is not valid.You are attempting to assign a
char[]array to acharvariable. The correct form would be one of the following:Given your invalid
arrassignment, your runtime error is most likely caused bymystrlenattempting to incorrectly deferencearr.What compiler are you using? Most conforming compilers should have caught the second issue. If using GCC, add the
-Wallflag to your makefile.