1

How should I return an empty string from a function? I tried using lcp[i] = ' ' but it creates an error. Then I used lcp[i] = 0 and it returned an empty string. However, I do not know if it's right.

Also, is it necessary to use free(lcp) in the caller function? Since I could not free and return at the same time.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 50
char *find_LCP(char str1[], char str2[]);

char *find_LCP(char str1[], char str2[]){

    char * lcp = malloc(MAX_LEN * sizeof(char));

    int a = strlen(str1);
    int b = strlen(str2);
    int min = a < b ? a : b;

    for(int i = 0; i < min; i++){
        if(str1[i] == str2[i])
            lcp[i] = str1[i];
        else
            lcp[i] = 0;
    }

    return lcp;
}

int main()
{
    char str1[MAX_LEN], str2[MAX_LEN];
    char * lcp;

    printf("Enter first word > ");
    scanf("%s", str1);
    printf("Enter second word > ");
    scanf("%s", str2);

    lcp = find_LCP(str1, str2);
    printf("\nLongest common prefix: '%s'\n", lcp);

    free(lcp);
    return 0;
}
1
  • 1
    Simple way, after char * lcp = malloc(MAX_LEN * sizeof(char)); just add *lcp = 0; and regardless what happens in the loop, even if min == 0, you are guaranteed to return an empty-string. (you can also just change malloc to calloc) As is, you should move int i = 0; outside the loop declaration and add lcp[i] = 0; after you exit the loop -- that will ensure your string is nul-terminated in all cases as well (empty or not) Commented Jan 13, 2021 at 8:23

4 Answers 4

2

An "empty" string is just a string with the first byte zero, so you can write:

s[0] = 0;

However, it is not clear what you are trying to do. The LCP of "foo" and "fob" is "fo", not the empty string.

You can also return as soon as you find the first non-matching character, no need to go until the end.

Further, you can simply pass the output string as a parameter and have lcp be an array. That way you avoid both malloc and free:

char lcp[MAX_LEN];
...
find_LCP(lcp, str1, str2);
Sign up to request clarification or add additional context in comments.

1 Comment

I already tried to run this code and it works. For example, I entered "breath" and "breeze" it returns "bre". However, if I try to enter "hello" and "world" since they have no common prefix it should return an empty string. If I tried to remove the code lcp[i] = 0, it will spit out random characters.
0

If you want to empty a string without using a for loop then you can do

lcp[0] = 0

but for emptying a string it was right the way you did using a for loop.

There are plenty other ways of emptying the string word by word using for loop:

lcp[i] = '\0';

and it's the right way to make string empty as letter by letter you trying to do using for loop But if you are not using some loops and simply empty a string then you can do this.

memset(buffer,0,strlen(buffer));

but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use:

memset(buffer,0,sizeof(buffer));

1 Comment

strcpy(lcp[i],"\0") is obviously not correct.
0

Your program has a bug: If you supply two identical strings, lcp[i] = 0; never executes which means that your function will return a string which is not NUL-terminated. This will cause undefined behvaior when you use that string in your printf in main.

The fix for this is easy, NUL-terminate the string after the loop:

int i;
for (i = 0; i < min; i++){
    if(str1[i] == str2[i])
        lcp[i] = str1[i];
    else
        break;
}

lcp[i] = 0;

As for the answer to the question, an empty string is one which has the NUL-terminator right at the start. We've already handled that as we've NUL-terminated the string outside the loop.

Also, is it necessary to use free(lcp) in the caller function?

In this case, it is not required as the allocated memory will get freed when the program exits, but I'd recommend keeping it because it is good practice.


As the comments say, you can use calloc instead of malloc which fills the allocated memory with zeros so you don't have to worry about NUL-terminating.

Comments

0

In the spirit of code golf. No need to calculate string lengths. Pick any string and iterate through it until the current character either null or differs from the corresponding character in the other string. Store the index, then copy appropriate number of bytes.

char *getlcp(const char *s1, const char *s2) {
    int i = 0;

    while (s1[i] == s2[i] && s1[i] != '\0') ++i;

    char *lcp = calloc((i + 1), sizeof(*lcp));
    memcpy(lcp, s1, i);
    return lcp;
}

P.S. If you don't care about preserving one of input strings then you can simplify the code even further and just return the index (the position of the last character of the common prefix) from the function, then put '\0' at that index into one of the strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.