Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

K&R Exercise 5-5 strcpy Segmentation fault

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading