Skip to content

c_new undefined behavior #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ethana56 opened this issue Feb 15, 2025 · 2 comments
Closed

c_new undefined behavior #120

ethana56 opened this issue Feb 15, 2025 · 2 comments

Comments

@ethana56
Copy link

ethana56 commented Feb 15, 2025

Hello,
It seems that the c_new macro invokes undefined behavior when malloc returns NULL because passing NULL to memcpy is undefined behavior.

@ethana56
Copy link
Author

ethana56 commented Feb 22, 2025

I also see similar code in cstr_reserve:

    if (cap > cstr_s_cap) {
        char* data = (char *)i_malloc(cap + 1);
        const isize len = cstr_s_size(self);
        /* copy full short buffer to emulate realloc() */
        c_memcpy(data, self->sml.data, c_sizeof self->sml);
        self->lon.data = data;
        self->lon.size = (size_t)len;
        cstr_l_set_cap(self, cap);
        return data;
    }
    return self->sml.data;

data might be NULL if i_malloc returns NULL, which will invoke undefined behavior. Should functions that call malloc check for NULL and return early with a return value of NULL or false?

@tylov
Copy link
Collaborator

tylov commented Apr 9, 2025

Hi, yes return NULL for reserve and a few others. There is an accepted proposal to make this non-UB in C2y, but for now it should be fixed with a separate commented check which can be easily removed later. This issue also includes possible (NULL + 0) expressions to be UB.

tylov pushed a commit that referenced this issue Apr 12, 2025
@tylov tylov closed this as completed Apr 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants