简体   繁体   English

复制到缓冲区期间出现分段错误错误

[英]Segmentation fault error during the copying to buffer

I write code: 我写代码:

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

int main(){
        char * var=(char*) calloc(10, sizeof(char));
        strncpy(var,"123456789",9);
        strncpy(var, "abcdefghi",1000000 );
        printf("This is var == %s\n",var);

}

but after compiling and running him I have Segmentation fault error. 但是在编译并运行他后,我Segmentation fault错误。 If I change maximum copy character in the line strncpy(var, "abcdefghi",1000000) to 10 then it's work fine. 如果我将strncpy(var, "abcdefghi",1000000)行中的最大复制字符更改为10,则可以正常工作。 But I really don't understand why segmentation fault error is occurring in my case. 但是我真的不明白为什么我的情况下会发生segmentation fault错误。

strncpy always pads up to the end of the buffer, so this line: strncpy始终strncpy到缓冲区的末尾,因此此行:

 strncpy(var, "abcdefghi",1000000 );

causes the segfault. 导致段错误。

As you can read here The remainder of the buffer is filled with \\0 . 正如你可以看到这里的缓冲区的其余部分填充\\0

Because you allocate 10 bytes: 因为您分配了10个字节:

char * var=(char*) calloc(/*HERE->*/10, sizeof(char));

and try to copy 1000000 bytes to it. 并尝试向其复制1000000字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM