我使用 malloc 为 x 分配 n(y 的字符串长度)字节。但是,在将 y 复制到 x 之后,我在 x 中添加了 3 个字符,包括 '\0' 并且我没有收到任何错误。
由于我分配的空间仅可容纳 10 个字符,因此在尝试将值分配给未分配的内存时不应该出现错误吗?这是未定义的行为吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int *argc,char **argv)
{
char *x,*y="123465412";
int i,n;
n=strlen(y);
x=(char *)malloc(sizeof(char)*n);
for(i=0; i<n ; i++)
x[i]=y[i];
x[i]='5';
x[i+1]='5';
x[i+2]='\0';
puts(x);
}