[英]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
错误。
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.