Skip to content

String overflows #686

@averater

Description

@averater

There are multiple possible string overflow issues. One recent commit tried to solve two cases but used the wrong length: 0d76220

On my compiler I get this warning: stringop-overflow.

This should be solved by either double-checking all strcpy and strncpy so the buffer definitely have enough space for the trivial cases with known lengths or by checks of available buffer for the non-trivial cases

Here is some code to explain the issues:

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

int avail(char buf[], int l) {
    int ret = l - strlen(buf) - 1;
    if (ret<0) return 0;
    return ret;
}
int main(void) 
{
    {
        char str1[4] = "abc";
        char str2[5] = "def";
        strcat(str1, str2);
        strcat(str1, "...");
        puts(str1);  // Buffer overflow!
    }{
        char str1[4] = "abc";
        char str2[5] = "def";
        strncat(str1, str2, strlen(str2));
        strncat(str1, "...", 3);
        puts(str1);  // Buffer overflow!
    }{
        char str1[8] = "abc";
        int l = sizeof(str1)/sizeof(*str1);
        char str2[3] = "def";  // not null terminated
        strncat(str1, str2, avail(str1, l));
        strncat(str1, "...", avail(str1, l));
        puts(str1);  // Undefined
    }{
        char str1[8] = "abc";
        int l = sizeof(str1)/sizeof(*str1);
        char str2[4] = "def";
        strncat(str1, str2, avail(str1, l));
        strncat(str1, "...", avail(str1, l));
        puts(str1);  // OK
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions