skalion
skalion

Reputation: 37

Write a function that removes the last char from a String in C. Segmentation fault (core dumped) Error

I am trying to implement the function as explained in the subject, but I get the error: Segmentation fault (core dumped). What is my mistake?

char* removelast(char* s) {
   char* r = s; 
   while (*s) {
       s++;
   }
   s--;
   *s = '\0';
   return r;
}

Upvotes: 1

Views: 182

Answers (1)

Alex Lop.
Alex Lop.

Reputation: 6875

The following code has several issues:

char* removelast(char* s) {
   char* r = s; 
   while (*s) {
       s++;
   }
   s--;
   *s = '\0';
   return r;
}
  1. It doesn't check for input validity like s==NULL
  2. If the input is an empty string (as was remarked by @Swordfish in the comments) this code will invoke undefined behavior.
  3. If the input is const char * (like "Hello World!") this code also invokes undefined behavior.

I would suggest to change the function signature to char *removeLast(const char * s), check for input validity, allocate new buffer for the string without the last character. Copy the required characters from s to the new string and return its pointer.

Something like that (hope it works, didn't check it)

char *removeLast(const char *s)
{
    char *newStr = NULL;
    size_t sLen; // length of the 's' string

    // check for 's' validity (not NULL and not empty) and successful 'malloc'
    if ( s && (sLen = strlen(s)) && (newStr = malloc(sLen)) )
    {
        int res = strcpy_s(newStr, sLen - 1, s);
        if (!res)
        {
            newStr[sLen - 1] = '\0';
        }
        else // strcpy_s error
        {
            free(newStr);
            newStr = NULL;
        }
    }

    return newStr;
}

Upvotes: 1

Related Questions