strcpy()/strncpy() crashes on structure member with extra space when optimization is turned on on Unix?

前端 未结 6 1637
再見小時候
再見小時候 2021-02-06 23:34

When writing a project, I ran into a strange issue.

This is the minimal code I managed to write to recreate the issue. I am intentionally storing an actual string in the

6条回答
  •  眼角桃花
    2021-02-06 23:41

    Your pointer p->c is the cause of crash.
    First initialize struct with size of "unsigned long long" plus size of "*p".
    Second initialize pointer p->c with the required area size. Make operation copy: strcpy(p->c, str);
    Finally free first free(p->c) and free(p).
    I think it was this.
    [EDIT]
    I'll insist. The cause of the error is that its structure only reserves space for the pointer but does not allocate the pointer to contain the data that will be copied.
    Take a look

    int main() 
    {
        pack *p;
        char str[1024];
        gets(str);
        size_t len_struc = sizeof(*p) + sizeof(unsigned long long);
        p = malloc(len_struc);
        p->c = malloc(strlen(str));
        strcpy(p->c, str); // This do not crashes!
        puts(&p->c);
        free(p->c);
        free(p);
        return 0;
    }

    [EDIT2]
    This is not a traditional way to store data but this works:

        pack2 *p;
        char str[9] = "aaaaaaaa"; // Input
        size_t len = sizeof(pack) + (strlen(str) + 1);
        p = malloc(len);
        // Version 1: crash
        strcpy((char*)p + sizeof(pack), str);
        free(p);
    
    

提交回复
热议问题