Home > other >  Unit testing for a function (tolower) using pointers
Unit testing for a function (tolower) using pointers

Time:01-27

I have this function that changes the string to all lower cases.

I am trying to create a unit test for this function, but I think I am passing the argument wrong, and I get this error.

Segmentation Fault (core dumped)

This is my code.

void example (char const * str1, int length, char * str2) {
    int i;
    for(i = 0; i < length; i  ) {
        *(str2   i) = putchar(tolower( *(str1   i) ));
    }
}

void testexample() {
    char * str1 = "TEST";
    char * str2 = "";
    example( str1, 4, str2);
    printf("%s\n", *str2);
}

int main() {
    testexample();
    return 0;
}

str1 is the original string, and n is the length of the string, and str2 is the all lower case version of str1.

I've been stuck trying to solve this problem for a while now.

I appreciate any help. Thank you.

CodePudding user response:

In your main:

char * str2 = "";

and then you pass str2 as a parameter, but it has too little storage and that storage is further read-only memory (points to a literal). The result is your crash. Use:

char str2[32] = 0;

or any length you need, including a null terminating character.

CodePudding user response:

also you write printf("%s", *str2). if str2 is a string so *str2 is a char.

  • Related