C结构破解工作 [英] C struct hack at work

查看:100
本文介绍了C结构破解工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在使用C结构黑客可以如何使用分配的额外的内存?

问题:

我有以下的C结构黑客实施。我的问题是如何使用,我已经与黑客分配的额外的内存。是否有人可以给我一个例子使用了额外的内存?

 #包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释的main()
{    结构MYSTRUCT {        INT LEN;
        炭chararray [1];    };    结构MYSTRUCT * PTR =的malloc(sizeof的(结构MYSTRUCT)+ 10 - 1);
    ptr->的len = 10;
    ptr-> chararray [0] ='A';
    ptr-> chararray [1] ='B';
    ptr-> chararray [2] ='c'的;
    ptr-> chararray [3] ='D';
    ptr-> chararray [4] ='E';
    ptr-> chararray [5] = f的;
    ptr-> chararray [6] =G;
    ptr-> chararray [7] =H;
    ptr-> chararray [8] ='我';
    ptr-> chararray [9] ='J';
}


解决方案

是的,这是(并且是)在 C 的标准方式创建和处理variably-大小结构

这例子是一个有点冗长。大多数程序员会更巧妙地处理它:

 结构MYSTRUCT {
        INT LEN;
        炭chararray [1]; //有些编译器允许[0]这里
    };
    字符*味精=ABCDEFGHI;
    INT N = strlen的(MSG);    结构MYSTRUCT * PTR =的malloc(sizeof的(结构MYSTRUCT)+ N + 1);    ptr-> LEN = N;
    的strcpy(ptr-> chararray,味精);
}

Is this how one can use the the "extra" memory allocated while using the C struct hack?

Questions:

I have a C struct hack implementation below. My question is how can I use the "extra" memory that I have allocated with the hack. Can someone please give me an example on using that extra memory ?

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

int main()
{

    struct mystruct {

        int len;
        char chararray[1];

    };

    struct mystruct *ptr = malloc(sizeof(struct mystruct) + 10 - 1);
    ptr->len=10;


    ptr->chararray[0] = 'a';
    ptr->chararray[1] = 'b';
    ptr->chararray[2] = 'c';
    ptr->chararray[3] = 'd';
    ptr->chararray[4] = 'e';
    ptr->chararray[5] = 'f';
    ptr->chararray[6] = 'g';
    ptr->chararray[7] = 'h';
    ptr->chararray[8] = 'i';
    ptr->chararray[9] = 'j';


}

解决方案

Yes, that is (and was) the standard way in C to create and process a variably-sized struct.

That example is a bit verbose. Most programmers would handle it more deftly:

struct mystruct {
        int len;
        char chararray[1];  // some compilers would allow [0] here
    };
    char *msg = "abcdefghi";
    int n = strlen (msg);

    struct mystruct *ptr = malloc(sizeof(struct mystruct) + n + 1);

    ptr->len = n;
    strcpy (ptr->chararray, msg);
}

这篇关于C结构破解工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆