Undefined behavior of array copy of c language

Asked 2 years ago, Updated 2 years ago, 29 views


with the following array copy code using memcpy in C language. In the code below, I wanted to duplicate the destination and the source of the copy by copying it from the first address of the buf, causing undefined behavior.

·I am not sure if this is an example of an appropriate undefined behavior.Also, I would like you to briefly tell me why this is the result.
·Also, I wrote the code in imitation of the appearance, but if you have a simpler code, please let me know

#include<stdio.h>
# include <string.h>

void*memcpy(void*dst, const void*src, size_tn){
        size_ti;
        char*p1 = dst;
        const char*p2 = src;

        for(i=0;i<n;++i){
                *p1 = *p2;
                ++p1;
                ++p2;
        }
}

int main(void){
        char buf [ ]={0,1,2,3,4};
        char buf2[5];

        memcpy(buf+1,buf,sizeof(buf));

        for(inti=0;i<sizeof(buf);++i){
                printf("%d\n", buf[i]);
        }

        return 0;
}

The results are as follows:

0
0
1
2
3
*** stack smashing detected ***:<unknown>terminated
Aborted (core dumped)

c

2022-09-29 21:41

1 Answers

The presentation code is causing great undefined behavior.

  • Writing to buf[5]
  • I define a function with the same name as the standard built-in function

See C: Array subscripts for the technical term undefined behavior, so programs that perform undefined behavior do not always work as you wish.In fact, the [c++] x86 Debug Build in Visual Studio 2019 Version 16.11.6 shows 000 and the debugger shows Run-Time Check Failure #2-Stackaround the variable 'buf' was corrupted..It seems that memory corruption was detected afterwards.

I don't know if it's an example of an undefined behavior.

There is no such thing as "appropriate undefined behavior" because undefined behavior is caused by improper programs.Smart compilers these days

int main(){
    char buf[5];
    buf[5] = '\0';
}

The old embedded compiler can detect errors, but it's hard to detect because it's harmless enough to destroy unused areas on the stack without any compilation or execution.


2022-09-29 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.