gpt4 book ai didi

c - [strcat&malloc&free],当我使用 strcat() 时,指针似乎不是 NULL,即使我故意将其设为 NULL(没有额外赋值)?

转载 作者:太空宇宙 更新时间:2023-11-04 07:47:07 25 4
gpt4 key购买 nike

<分区>

如题,我做了一个demo来说明一下我的困惑。

如果我将 [strcat ] 替换为 [stacpy],我可以得到显而易见的结果,即

@

@

@

所以我怀疑问题出在 [strcat] 上。

void main(){
for(int i=0; i<3 ;i++){

char* str = (char*)malloc(200*sizeof(char));

if(str == NULL){
printf("malloc failed. \n");
return;
}

strcat(str, "@ ");
printf("%s\n", str);

free(str);
str = NULL;
}
}

在我的期望中,我应该得到:

@

@

@


但我得到的是:

(1)@

xK`▒

xK`▒

每次都不一样:

(2)@

x▒

x▒

(3)@

xk▒▒

xk▒▒

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com