Reputation: 37
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
Reputation: 6875
The following code has several issues:
char* removelast(char* s) {
char* r = s;
while (*s) {
s++;
}
s--;
*s = '\0';
return r;
}
s==NULL
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