My code does not work. I get run time error at the moment i accept a string. What is the problem with this code?
//this is what i have in main()
char *ele,*s[max];
int *count,temp=0;
count=&temp;
printf("Enter string to insert: ");
scanf("%s",ele);
addleft(s,ele,count);
//following is the function definition
void addleft(char *s[max],char *ele,int *count)
{
int i;
if((*count)==max)
{
printf("Queue full!\n");
return;
}
for(i=*count;i>0;i--)
strcpy(s[i],s[i-1]);
strcpy(s[0],ele);
(*count)++;
printf("String inserted at left!\n");
}
eleis an uninitialisedchar*and has no memory associated with it andscanf()will be attempting to write to it causing undefined behaviour, a segmentation fault is probable.You need to either dynamically allocate memory for
eleor declare a local array and prevent buffer overrun when usingscanf():Additionally, the function
addleft()is usingstrcpy()ons, which is an array ofchar*and each of thechar*in the array is unitialised. This is undefined behaviour and a probable segmentation fault. To correct, you could usestrdup()if it is available otherwisemalloc()andstrcpy():Note that the
forloop inside theaddleft()function is dangerous as thechar*contained withinsare not necessarily of the same length. This could easily lead to writing beyond the end of arrays. However, as the elements are addresses of dynamically allocatedchar*you can just swap the elements instead of copying their content.