分段故障(核心倾倒)错误未解决

Segmentation fault (core dumped) error not resolved

本文关键字:错误 未解决 故障 核心 分段      更新时间:2023-10-16
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
int i,n;
char * buffer=NULL;
i=0;
cout<<"enter the character length you wish to store dynamically"<<endl;
cin>>i;
buffer= (char*) malloc(i+1);
if(buffer=NULL)
exit(1);
for(n=0;n<i;++n)
buffer[n]=rand()%26+'a';
buffer[i]='';
cout<<"the string is "<<buffer<<endl;
free(buffer);
return 0;}

我正在得到分割错误:输出:输入您希望动态存储的角色长度5分段故障(核心倾倒)我无法弄清楚我犯的错误?我试图以调试模式运行,但是没有生成核心文件。请建议解决方案。

buffer=NULL是一个分配。它将被评估为false,buffer[n]=rand()%26+'a';将取消分配的NULL

做比较 buffer==NULL