im working my way through the K&R C programing language book and trying to implement my own version of the function strncpy according to the description in exercise 5 at chapter 5:
strncpy(s,t,n) copies at most n characters of t to s
I have tried to write the following:
#include <stdio.h>
void *strn_cpy(char *dest, const char *src, int n){
while ((*dest = *src ) && n--);
}
int main(){
char * s1 = "hello";
char * s2 = "abc";
strn_cpy(s1, s2, 2);
printf("%s", t1);
}
The code above returns a Segmentation fault error and I cant seem to figure out why, the way I understand the function is that with each iteration of the loop, the current value of *src is copied onto *dest, afterwards both pointers locations are incremented by 1. Then, if the value of *src is equal to '\0' or if n equals to 0 then the loop breaks. Thanks.
CodePudding user response:
char *s = "some string"
creates a pointer to a string literal that you cannot change. You're getting a seg fault because you're trying to write to a read only string. Change it to char s[number]
#include <stdio.h>
void *strn_cpy(char *dest, const char *src, int n) {
while (n-- && (*dest = *src ));
}
int main() {
char s1[6] = "hello";
char *s2 = "abc";
strn_cpy(s1, s2, 2);
printf("%s", s1);
}