momonosuke
momonosuke

Reputation: 57

cutting a string when a character is found

I wrote a function that cuts the string "hello world" to "hell" if a 'o' is found.

I keep getting a segmentation fault. I don't know where the mistake could be. Could anyone help? Thank you in advance.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* cutString(char* str, char del){

    char *newstring =(char*) str;
    malloc(sizeof(char)*strlen(str));
    int i= 0;

    for(; newstring[i]!='\0'&&newstring[i]!=del;i++);

    if(i==strlen(newstring))
     printf("not found");
     else
     newstring[i]='\0';

    return newstring;
}


int main(){



    cutString("Hello World",'o');

    return 0;

}

Upvotes: 0

Views: 136

Answers (3)

manjy
manjy

Reputation: 109

 newstring[i]='\0';

This line is invalid. Modifying string literals is undefined behavior. I would suggest check this out :segmentation fault when using pointer

A better solution would be to use arrays instead of pointers

Upvotes: 1

4386427
4386427

Reputation: 44340

There are a number of problems in your code. The main problem is that you don't assign the return value from malloc to newstring. Besides that you need to malloc an extra byte for the string termination.

Further, your loop must copy characters from str into newstring.

In main you must assign the return value from the function to a char pointer variable to get hold of the new string.

Something like:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* cutString(char* str, char del){

    char *newstring = malloc(strlen(str) + 1);  // malloc into newstring
    int i= 0;

    while (newstring[i]!='\0' && str[i] != del)  // Stop when a) no more chars in str or b) "del" is found
    {
        newstring[i] = str[i];     // Copy character from str to newstring
        ++i;
    }

    newstring[i]='\0';  // Terminate the string

    return newstring;
}


int main(){
    char* newstring = cutString("Hello World",'o');  // Save the returned value
    printf("%s\", newstring);
    free(newstring);
    return 0;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409472

There are two major problems with your code:

  1. char *newstring =(char*) str makes newstring point to the old str. And since you pass a literal string (which is read only) you will have undefined behavior attempting to modify it.

  2. malloc(sizeof(char)*strlen(str)); is a memory leak. And doesn't allocate space for the terminator.

The crash is probably because point one, when you attempt to modify the read-only string literal.

Upvotes: 3

Related Questions