Struggling with strings. What is wrong with my function?

168 Views Asked by At

I am trying to write a small function to trim left spaces from a string, but I cannot get it right. In this version, I get the following error:

bus error: 10

Could anyone please explain to me what I am doing wrong? I am not looking so much for an alternative piece of code, but would like to understand the errors in my code:

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


void trim_string(char *);

int main(int argc, char *argv[]) {

    char *temp = "   I struggle with strings in C.\n";
    trim_string(temp);
    printf("%s", temp);

    return 0;
}


void trim_string(char *string) {
    char *string_trimmed = "";
    int i=0, j=0;

    while (isblank(string[i])) {
        i++;
    }
    while (string[i] != '\0') {
        string_trimmed[j] = string[i];
        i++;
        j++;
    }
    string_trimmed[j] = '\0';
    strcpy(string, string_trimmed);
}

I have now found a workaround solution, shown below. But I am still not very clear about what I did wrong in the first place:

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

#define MAX_LENGTH 100

void trim_string(char [MAX_LENGTH]);

int main(int argc, char *argv[]) {

    char temp[MAX_LENGTH] = "   I struggle with strings in C.\n";
    trim_string(temp);
    printf("%s", temp);

    return 0;
}


void trim_string(char string[MAX_LENGTH]) {
    char string_trimmed[MAX_LENGTH];
    int i=0, j=0;

    while (isblank(string[i])) {
        i++;
    }
    while (string[i] != '\0') {
        string_trimmed[j] = string[i];
        i++;
        j++;
    }
    string_trimmed[j] = '\0';
    printf("c\n");
    strcpy(string, string_trimmed);
}
1

There are 1 best solutions below

0
On

Both string and string_trimmed point to string literals, here in main:

char *temp = "   I struggle with strings in C.\n";
             ^
             |
             This is a string literal

temp points to a string literal and the standard says you are not allowed to modify them.

In the function trim_string you are modifying a them which is undefined behavior of which a bus error is one possible result, although anything can happen.

string_trimmed either needs to be an array like this:

char string_trimmed[n] ;

where n is the size of your input using strlen(string) would probably make sense or dynamically allocated via malloc which you would need to free at the end of your function. The same things goes for your input from main, this would work as a substitute:

char temp[] = "   I struggle with strings in C.\n";

For completeness sake, the draft C99 standard section 6.4.5 String literals paragraph 6 says (emphasis mine):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.