Home > Blockchain >  unable to test the non standard function strlcpy
unable to test the non standard function strlcpy

Time:06-28

I am trying to create my own implementation of strlcpy but first, I wanted to test the original function.

When I try to compile my code with gcc -Wall -Wextra -Werror ft_strlcpy.c, I get this:

/usr/bin/ld: /tmp/ccaTaHki.o: in function `test':
ft_strlcpy.c:(.text 0x59): undefined reference to `strlcpy'
collect2: error: ld returned 1 exit status

This is my code sample for testing the function:

#include <stdio.h>
#include <bsd/string.h>

void test(int size)
{
    char string[] = "Hello there, Venus";
    char buffer[19];
    int r;

    r = strlcpy(buffer, string, size);

    printf("Copied '%s' into '%s', length %d\n", string, buffer, r);
}

int main()
{
    test(19);
    test(10);
    test(1);
    test(0);

    return (0);
}

What am I doing wrong how can I test it?

CodePudding user response:

When I try to compile my code with gcc -Wall -Wextra -Werror ft_strlcpy.c, I get this:

/usr/bin/ld: /tmp/ccaTaHki.o: in function `test':
ft_strlcpy.c:(.text 0x59): undefined reference to `strlcpy'
collect2: error: ld returned 1 exit status

That is a linker error, indicating that the function you are trying to call is not found in your code or in any of the libraries being linked, including the C standard library.

Having recognized that, the (Linux) manual page for strlcpy() quickly yields a probable reason and solution where it says, near the top:

Library

Utility functions from BSD systems (libbsd, -lbsd)

Supposing that that documentation is relevant to you, which it probably is if you are compiling with gcc, it tells you not only what library but exactly what link option to use: -lbsd. Therefore, compile your code this way:

gcc -Wall -Wextra -Werror ft_strlcpy.c -lbsd

That works for me.

CodePudding user response:

Your quick test is somewhat unreliable because buffer is uninitialized so the output is unpredictable for the last test.

Here is a modified version with more explicit output:

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

void test(int size) {
    char string[] = "Hello there, Venus";
    char buffer[20] = "xxxxxxxxxxxxxxxxxxx";
    int r = strlcpy(buffer, string, size);
    int len = strlen(buffer);

    printf("Source: '%s', size: %d, buffer: '%s', len: %d, result: %d\n",
           string, size, buffer, len, r);
}

int main() {
    test(19);
    test(10);
    test(1);
    test(0);
    return 0;
}

Output:

Source: 'Hello there, Venus', size: 19, buffer: 'Hello there, Venus', len: 18, result: 18
Source: 'Hello there, Venus', size: 10, buffer: 'Hello the', len: 9, result: 18
Source: 'Hello there, Venus', size: 1, buffer: '', len: 0, result: 18
Source: 'Hello there, Venus', size: 0, buffer: 'xxxxxxxxxxxxxxxxxxx', len: 19, result: 18
  •  Tags:  
  • c
  • Related