Hello I am trying to remove the first word in a string. For example: buffer = "Hello my name is Code"
After implementing removeToken()
, buffer should now be "my name is Code"
.
The code I have currently is giving me a segmentation fault.
I have the following:
char *buffer = NULL;
char *buffercopy = NULL;
void startBuffer(char *inputLine) {
int length = strlen(inputLine);
buffer = (char *)malloc(length);
buffercopy = (char *)malloc(length);
strcpy(buffer, inputLine);
strcpy(buffercopy, inputLine);
}
char *removeToken() {
/* removes the first token from the buffer, buffer is reduced in size */
char *token;
char delimiters[2] = " ,";
int origLen = strlen(buffer);
token = strtok(buffer, delimiters);
printf("%s \n", token);
int p = strlen(token);
int i = 0;
while (buffer[i] != '\0') {
buffer[i] = buffer[i + p];
i++;
}
return buffer;
}
There are multiple problems in your code:
you do not allocate enough memory to copy the strings, you must allocate one extra byte for the null terminator:
void startBuffer(char *inputLine) {
int length = strlen(inputLine);
buffer = (char *)malloc(length + 1);
buffercopy = (char *)malloc(length + 1);
strcpy(buffer, inputLine);
strcpy(buffercopy, inputLine);
}
Note that the above code can be simplified to this:
void startBuffer(const char *inputLine) {
buffer = strdup(inputline);
buffercopy = strdup(inputline);
}
In removeToken
, you allocate the separator string with:
char delimiters[2] = " ,";
This is incorrect as you need a third byte for the '\\0'
null terminator. You can write this instead:
char delimiters[] = " ,";
You only count the length of the initial string, not the separators, the first of which has been changed to a '\\0'
.
The copy loop therefore stops immediately.
You also forget to copy the final '\\0'
in the copy loop.
Here is a corrected version:
char *removeToken(char *buffer) {
const char *delimiters = " ,";
size_t i, skip;
skip = strcspn(buffer, delimiters); /* skip the word */
skip += strspn(buffer + skip, delimiters); /* skip the delimiters */
for (i = 0; buffer[skip + i] != '\0'; i++) {
buffer[i] = buffer[skip + i];
}
buffer[i] = '\0';
return buffer;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.