Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlayone/72144bd1d9bb01844e7d to your computer and use it in GitHub Desktop.
Save superlayone/72144bd1d9bb01844e7d to your computer and use it in GitHub Desktop.
Struct traits

##Struct traits

在《Inside The C++ Object Model》这本书中有一个例子很有趣,就是在struct中放置一个一个元素的char数组,在运行时动态的构造可变长数组,如下:

    struct mumble{
    	/*stuff*/
    	char pc[1];
    };
    typedef struct mumble* mumble_ptr;
    mumble_ptr resize_mum_t(int size){
    	return (mumble_ptr) malloc(sizeof(mumble) + size);
    }

在运行时调用如下:

    char test[] = "Hello world!";
	mumble_ptr p = resize_mum_t(strlen(test)+1);
	strcpy(p->pc,test);

那么p就指向了malloc出来的一块连续内存区域。这块内存全部处于堆上,而p->pc指向的是这块内存的首地址,因为malloc操作分配了足够的内存,所以在strcpy时,虽然溢出了pc的内存范围,但没有溢出struct的内存范围,使得strcpy的结果是合理的和可控的。这样一来,相当于struct拥有了可变大小的数组,更加灵活。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment