Why segmentation error when copying memory

I run ubuntu on x86_32 ... and I continue to get a segmentation error while running this program.

enter code here #include<stdio.h> #include<stddef.h> char *memcp(char *dest, const char *src, size_t n) { char *dp = dest; const char *sp = src; while(n--) *dp++ = *sp++; return dest; } int main() { char *s = "abcde"; char *d; char *r = memcp(d,s,6); printf("%s",r); return(0); } 

The problem with this code is that it runs on my friend's x86_64 machine on windows as well as on ubuntu. Please help me.

+2
source share
1 answer

There are at least two ways to do this:

malloc method:

 int main(void) { char *s = "abcde"; char *d = malloc(6); char *r = memcp(d, s, 6); printf("%s",r); free(d); return(0); } 

Array Method:

 int main(void) { char *s = "abcde"; char d[6]; memcp(d, s, 6); return 0; } 

Please note that it is generally not recommended to write long code buffer lengths into your code (for example, you strictly encode 6). If the size of your input changes and you forget to update the number 6, problems will arise.

The reason you get the segmentation error is because the d pointer doesn't point anywhere. In your memcp function memcp you are trying to write this pointer, but since this does not indicate that your program will fail. In the C standard, this is called undefined behavior, and basically it means that anything can happen.

You might also be interested in the fact that the C standard library already has two functions, memmove and memcpy . memmove is useful if the source and destination areas overlap. If you know that they will never overlap, memcpy may be faster.

Finally, I would like to point out that you should not take advice from Arthur regarding the use of an uninitialized pointer. You should never rely on the value of an uninitialized pointer, which means that your program behavior is undefined. Appendix C of the C language specification mentions the following: undefined behavior :

J.2 undefined Behavior

  • Undefined behavior in the following cases:
    • & hellip;
    • The value of an object with automatic storage duration is used while it is undefined.
    • & hellip;
+7
source

Source: https://habr.com/ru/post/1268635/


All Articles