473,657 Members | 2,753 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

substitute for string 0 termination

The C-faq says that "The malloc/free implementation remembers the size
of each block allocated and returned, so it is not necessary to remind
it of the size when freeing."

Could that length information somehow be used as a substitute for
0-termination of strings?

Felix
Nov 14 '05 #1
35 2567
Felix Kater wrote:
The C-faq says that "The malloc/free implementation remembers the size
of each block allocated and returned, so it is not necessary to remind
it of the size when freeing."

Could that length information somehow be used as a substitute for
0-termination of strings?

Felix


The length that the implementation keeps track of is the size of the
block allocated by malloc() which, assuming success, will be at least
the size you requested. Of course, you can store strings which are
shorter than this without any trouble, and the length will be different.
Furthermore, the way the implementation decides to keep track of the
size of the block returned by malloc() is up to the implementation. So
any hack which you discover for reading the actual size allocated is
completely non-portable. You could, however, use a structure where the
length (of the string) is stored, and use that instead of a terminating
0. However, since the C library functions require 0 termination for
strings, you'll have a much more difficult time passing the string to
these functions. It would make sense, though, to keep track of the
length if you anticipate repetetive calls to strlen() when the length is
not changing, thus avoiding needless O(n) operations.

Hope that helps,
--John
Nov 14 '05 #2
Yes, you could speed up length tests by storing the length before the
first character like this. The "fast" strings are still
zero-terminated, so they work with the CRT string functions.

char * makeFastString( char *regularString )
{
size_t len, *p;
len = strlen( regularString );
p = malloc( len + 1 + sizeof( size_t ) );
if( !p )
return NULL;
*p = len;
strcpy( (char *)( p + 1 ), regularString );
return (char *)( p + 1 );
}

size_t lengthOfFastStr ing( char *fastString )
{
size_t *p = (size_t *) fastString;
return *( p - 1 );
}

void deleteFastStrin g( char *fastString )
{
size_t *p = (size_t *) fastString;
free( p );
}

Nov 14 '05 #3
Oops typo: free( p ) should be free( p - 1 )

Nov 14 '05 #4
al******@hotmai l.com wrote:

Yes, you could speed up length tests by storing the length before the
first character like this. The "fast" strings are still
zero-terminated, so they work with the CRT string functions. void deleteFastStrin g( char *fastString )
{
size_t *p = (size_t *) fastString;
free( p );
}


I think

free(fastString );

is what you really want to use, instead of

deleteFastStrin g(fastString);

--
pete
Nov 14 '05 #5
Yeah there was a typo. Unfortunately you can't edit posts here.

Nov 14 '05 #6
al******@hotmai l.com writes:
Yeah there was a typo. Unfortunately you can't edit posts here.


Usenet has a `supersedes' feature that you could use.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #7
Mac
On Wed, 26 Jan 2005 00:11:28 +0100, Felix Kater wrote:
The C-faq says that "The malloc/free implementation remembers the size
of each block allocated and returned, so it is not necessary to remind
it of the size when freeing."

Could that length information somehow be used as a substitute for
0-termination of strings?

Felix


In some hypothetical alternate universe, the committee responsible for
defining the C programming language could have opted to handle strings
differently.

In the universe we actually inhabit, the size of a block returned by
malloc can never be accessed directly by the programmer if the code is to
remain portable.

In any event, there are plenty of times when you don't want to malloc a
chunk of memory to be exactly the size of your string.

However, you could always define a struct wrapper for your strings
which remembers how big they are. See the untested fragment below.

struct my_string
{
size_t size;
char *s;
};

struct my_string *new_my_string( size_t size)
{
struct my_string *new_string;

new_string = malloc(sizeof *new_string);
if (new_string == NULL)
return NULL;
new_string->s = malloc(size);
if (new_string->s == NULL)
{ free(new_string );
return NULL;
}
new_string->size = size;
return new_string;
}

That kind of thing.

--Mac

Nov 14 '05 #8
Felix Kater wrote:
The C-faq says that "The malloc/free implementation remembers the size
of each block allocated and returned, so it is not necessary to remind
it of the size when freeing."

Could that length information somehow be used as a substitute for
0-termination of strings?
...


No.

Firstly, C standard library does not provide user with any means to
access this information.

Secondly, memory allocation functions are not guaranteed to allocate
exactly the requested amount of memory. Successful allocation requiest
might allocate more memory than was actually requested, which is
perfectly legal in C.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #9

"Andrey Tarasevich" <an************ **@hotmail.com> schreef in bericht
news:10******** *****@news.supe rnews.com...
Firstly, C standard library does not provide user with any means to
access this information.
Secondly, memory allocation functions are not guaranteed to allocate
exactly the requested amount of memory. Successful allocation requiest
might allocate more memory than was actually requested, which is
perfectly legal in C.


I understand this of course, but still I'd like to know why a function like
memsize can't be introduced in the std library. Maybe more bytes are
allocated than requested, a program shouldn't invoke undefined behaviour
when those extra bytes are overwritten right.
I think a portable function like this could be easily added to C and it
would be used a lot considering how many people have asked for something
like this.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
22725
by: Espen Ruud Schultz | last post by:
Lets say I have a char pointer and an std::string. Is it possible to get a pointer to the std::string's "content" so that the char pointer can point to the same text? And vice versa; can I give the std::string a pointer and a length and then give the std::string control over the pointer and its content? I'm basically trying to avoid copying large text between an std::string and a char pointer, and vice versa. Is there anyhing in the...
4
9305
by: francescomoi | last post by:
Hi. I'm trying to remove some characters within a string and substitute others. For instance, I want to convert: John's new house, great ---> Johns-new-house-great I tried with: ----------------//------------------ int main() {
26
563
by: junky_fellow | last post by:
Consider the following piece of code: char *str = "Hello"; if (str = "Hello") printf("\nstring matches\n"); str is pointer to char and "Hello" is a string literal whose type is "array of char". How can we compare two different objects for equality ? Is some conversion is being done before that comparison ?
1
277
by: GB | last post by:
Hi, I have a structure which I want to pass as a pointer to a C dll. The problem is that C# adds '\0' character at the end of each string (which is contained in the struct). I understand that C# does it so that no null terminated strings are passed but I want to pass the strings without the padding. Example,
6
2733
by: copx | last post by:
Can you / are you supposed to free() string literals which are no longer needed? In my case I've menu construction code that looks like this: menu_items = list_new(); list_add(menu_items, "Item 1"); list_add(menu_items, "Item 2"); list_add(menu_items, "Item 3"); menu_create(menu_items, false)
669
25857
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Languageâ€, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
232
13242
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
0
1218
by: Rainman | last post by:
Hi! I'm new here, and I had my first encounter with this site yesterday, when I shamelessly copied Killer42's excellent code for reading a file using the Get method. Thanks! :-) It worked like a dream in Excel. I'm now using the code to read ID3V1 and ID3V2 tags form my mp3 collection. Then (if needed) I rename them, delete or add tags etc, etc. (All done 'offline' in the comfortable GUI of Excel - the files aren't touched until I'm...
13
1979
by: Logan Lee | last post by:
Hi. I've written a small program to learn to write in C. But unfortunately the output is all jumbled up and not nice. /* read_file.c The whole point of this code is to read the entire content from a file then arrange the data as a single string. */ #include <stdio.h> char* returnArrayFromFile(char* file_name) { // Try opening a file
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.