Reputation: 3440
#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]='\0';
cout<<"the string is "<<buffer<<endl;
free(buffer);
return 0;}
I am getting segmentation fault: Output: enter the character length you wish to store dynamically 5 Segmentation fault (core dumped) I am not able to figure out the mistake I did? I tried to run in debugger mode,but there were no core file generated for it.? Please suggest a solution to it.
Upvotes: 0
Views: 48
Reputation: 75062
buffer=NULL
is an assignment. It will be evaluated as false and buffer[n]=rand()%26+'a';
will dereference the assigned NULL
.
Do comparision buffer==NULL
instead.
Upvotes: 1