[Back to the c-list]  [Back to the c MAIN page]  [Back to the BASICS-technology PAGE] 

pns: c source code: tu-blk

Source code files (as raw text) - -[tu-blk.h]- (requires tu.h and tu.c) -[tu-blk.c]- (requires tu.h and tu.c) -[blk-test.c]- (mini demo application) On this page: {Intro} {} {} {} {} {} {} {} {References} {Links} (including c compilers, etc)

tu-blk.c

Basically, tu-blk.c allows you to allocate ascii/binary data blocks of any size - limited to (eg, DOS machines which can't address more than 32K - sometimes 64K). Binary data is difficult to handle since, in general we expect strings in C to be null-terminated 0x00 as the last character. Thus, we might have: char My_info[100]; And we can put the \0 anywhere in there. But, if we have: char *My_info; and allocate 100 chars, we can *accidentally* write past the end of the allocated space -- we can do this with the array, but we're usually carefull, with such things as char GG_input_buffer [256]; /* plenty of room */ #define DATA_STRING_SIZE 100 char My_info [DATA_STRING_SIZE]; char Your_info [DATA_STRING_SIZE]; ... etc ... if (strlen (GG_input) > DATA_STRING_SIZE) Error_exit ("My_info is too long, re-enter") etc.... else strcpy (My_info, GG_input); But, for binary data, we have to "think ahead a bit". The primary data struct is: /*=====================*/ struct Blk_struct /*=====================*/ { char *Blk_name; /* the name assigned to by the program */ int Blk_size; /* ammount allocated ~~ [0] .. [Blk_size -1] */ int Blk_char_count; /* how much data is in it right now */ char *Blk_data; char *Blk_start, *Blk_end; /* Memory boundaries */ char *Next_read, *Last_written; struct Blk_struct *Prev, *Next; /* link list thingies */ };

De-allocating a block

See the function: Deallocate_blk_struct() in tu-blk.c An important thing is if you DEALLOCATE the block (say memory is tight, and you pull in a block, and process it into its components and then you need to release the block, YOU HAVE to turn all of the non-terminal chars into a NOT the null char. THat is Xd = Blk_data; for (i=1 ; i < Blk_size ; i++) /* note the i=1 and NOT i=0 */ *Xd++ = ' '; *Xd = '\0'; /* terminate the last char with a 0x00 char. THEN you can de-allocate. If you don't and there ARE any embedded null chars (0x00), then the deallocate will stop there, and leave an irrecoverable fragment of memory "out there".

Refs


Links