Search code examples
cstringdeque

ERROR READING STRING


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");
}

Solution

  • ele is an uninitialised char* and has no memory associated with it and scanf() will be attempting to write to it causing undefined behaviour, a segmentation fault is probable.

    You need to either dynamically allocate memory for ele or declare a local array and prevent buffer overrun when using scanf():

    char ele[1024];
    if (1 == scanf("%1023s", ele))
    {
        /* Process 'ele'. */
    }
    

    Additionally, the function addleft() is using strcpy() on s, which is an array of char* and each of the char* in the array is unitialised. This is undefined behaviour and a probable segmentation fault. To correct, you could use strdup() if it is available otherwise malloc() and strcpy():

    /* Instead of:
           strcpy(s[0],ele);
       use:
     */
    s[0] = strdup(ele);
    

    Note that the for loop inside the addleft() function is dangerous as the char* contained within s are 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 allocated char* you can just swap the elements instead of copying their content.