<分区>
我使用 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);
}