1 c heap-memory dynamic-memory-allocation
我写代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
但在编译并运行他之后,我有Segmentation fault错误.如果我将行中的最大复制字符更改strncpy(var, "abcdefghi",1000000)为10,那么它可以正常工作.但我真的不明白为什么segmentation fault我的情况会发生错误.
strncpy 总是填充到缓冲区的末尾,所以这一行:
strncpy(var, "abcdefghi",1000000 );
Run Code Online (Sandbox Code Playgroud)
导致段错误.
正如您可以在这里阅读的那样,缓冲区的其余部分已经填满\0.
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |