简体   繁体   中英

How do I make my program abort (without any lib)

I have an exercise in class where I have to copy the strstr() function in C (from <string.h> library). Here is my code

char *ft_strcpy(char *dest, char *src)
{
    int i;

    i = 0;
    while (src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
    return (dest);
}

This code is fully functional but when I try with a dest string that is smaller than the src string, it shows an unpredictable result that ends up overwriting src too. The original strstr() function's answer to that is to abort program in that situation. How can I make my program abort given that I can't use the abort() function?

You must check your string. May be one of them is NULL.

When you do : While (str[i] ..)

You don't know if (str) is NULL or not.

Do : While (str && str[i] != '\\0')

It's better.

You can also check if dest is malloc fine because if you don't have any memory for your string dest you can't assign value.

I would suggest a compact implementation

char * ft_strcpy(char * dest, const char * src) {
    if (strlen(dest) < strlen(src)) { /* abort(); or exit(1); */ }
    char * s = dest;
    while (*dest++ = *src++);
    return s;
}

The actual bounds checking is implemented in the safer version of strcpy , ie strcpy_s . You can find an implementation in Safe C Library .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM