473,387 Members | 1,529 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Is memset used only for strings?

Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
memset(bit, 1, 10000*sizeof(int));
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009

Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.

Why is this happen? Do I misused memset or sth else?

Any help is appreciated. Thanks!

Dec 4 '05 #1
17 6272
Frederick Ding said:
Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
int *bit = malloc(10000 * sizeof *bit);

if(bit != NULL)
{
memset(bit, 1, 10000*sizeof(int));
Oops - that won't do what you were hoping.
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009

Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.


Observe this magic:

unsigned char *p = (unsigned char *)bit;
while(p < (unsigned char *)(bit + 1))
{
printf("%d\n", *p++)
}

This prints every byte in your first int. Try it, and I think you'll
understand all about memset.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Dec 4 '05 #2
Frederick Ding wrote:
Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
memset(bit, 1, 10000*sizeof(int));
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009

Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.

Why is this happen? Do I misused memset or sth else?

Any help is appreciated. Thanks!


Your call to memset() sets each byte to 1. Your ints probably occupies 4
bytes, so you initialize each int with bit patterns 0x01010101, which
equals 16843009.

Bjørn
Dec 4 '05 #3
"Frederick Ding" <di*******@gmail.com> writes:
Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
Don't cast the result of malloc. It can mask errors such as failing
to include <stdlib.h> or compiling C code with a C++ compiler.

The recommended idiom is:

int *bit = malloc(10000 * sizeof *bit);

You should check whether the malloc() call succeeded.
memset(bit, 1, 10000*sizeof(int));
This sets every byte of the array to 1.
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009

Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.


16843009 in hexadecimal is 0x01010101.

memset() sets every byte to a specified value. There's no equivalent
standard function to set every int to a specified value.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 4 '05 #4

"Frederick Ding" <di*******@gmail.com> wrote

Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.

Why is this happen? Do I misused memset or sth else?

Any help is appreciated. Thanks!

memset isn't a very useful function.
It sets every byte to a given value. The only practical use, really, is to
set memory to zero, unless, as you say, you happen to want a string of
asterisks or something.
You cannot set integers to a non-zero value.
You can set pointers to NULL and floating point values to zero, but not with
complete portability (the NULL pointer isn't always all bits zero).

Your best bet is to ignore it and use a for loop, setting your array to the
values you want.
Dec 4 '05 #5
"Malcolm" <re*******@btinternet.com> wrote in message
news:dm**********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com...
[snip]
memset isn't a very useful function.
I agree.
It sets every byte to a given value. The only practical use, really, is
to set memory to zero, unless, as you say, you happen to want a string of
asterisks or something.
You cannot set integers to a non-zero value.
AFAIK you can't portably set them to zero either, except possibly the
fixed-size ones added in C99 (uint32_t etc).
You can set pointers to NULL and floating point values to zero, but not
with complete portability (the NULL pointer isn't always all bits zero).


Neither, as I'm sure you meant, is a floating point all-bits-zero
necessarily equal to zero.

Alex
Dec 4 '05 #6

"Alex Fraser" <me@privacy.net> wrote
It sets every byte to a given value. The only practical use, really, is
to set memory to zero, unless, as you say, you happen to want a string of
asterisks or something.
You cannot set integers to a non-zero value.


AFAIK you can't portably set them to zero either, except possibly the
fixed-size ones added in C99 (uint32_t etc).

int array[100];

memset(array, 0, 100 * sizeof(int));

is guaranteed to produce an array to 100 integers of value 0, on an ANSI
system.
(However if technology changes so that for some reason it doesn't make sense
to have value zero all bits clear, the ANSI standard will be a dead letter).

Dec 4 '05 #7
Frederick Ding a écrit :
Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
memset(bit, 1, 10000*sizeof(int));
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009
Many things are missing. It may work or not...
Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.


Assuming the code is complete, yes there are. It will appears more
clearly like this:

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

int main(void)
{
size_t const size = 10000;
int* bit = malloc (size * sizeof *bit);

if (bit != NULL)
{
memset(bit, 1, size * sizeof *bit);
printf("%X %X %X\n"
, (unsigned) bit[1]
, (unsigned) bit[2]
, (unsigned) bit[size-1]);

free (bit), bit = NULL;
}

return 0;
}

1010101 1010101 1010101

see the pattern ?

--
A+

Emmanuel Delahaye
Dec 4 '05 #8
Frederick Ding a écrit :
Hi, guys,I met a problem, Please look at the problem below:

int* bit = (int*)malloc(10000*sizeof(int));
memset(bit, 1, 10000*sizeof(int));
printf("%d %d %d\n", bit[1],bit[2], bit[9999]);

Output: 16843009 16843009 16843009
Many things are missing. It may work or not...

Please don't forget to free what have been allocated :

<<SYSALLOC Bloc 003D4A70 (40000 bytes) malloc'ed at line 14 of 'main.c'
not freed>>
Obviously I set the bit[0] to bit[9999] to 1, but it outputs are not
1's.


Assuming the code is complete, yes there are. It will appears more
clearly like this:

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

int main(void)
{
size_t const size = 10000;
int* bit = malloc (size * sizeof *bit);

if (bit != NULL)
{
memset(bit, 1, size * sizeof *bit);
printf("%X %X %X\n"
, (unsigned) bit[1]
, (unsigned) bit[2]
, (unsigned) bit[size-1]);

free (bit), bit = NULL;
}

return 0;
}

1010101 1010101 1010101

see the pattern ?

--
A+

Emmanuel Delahaye
Dec 4 '05 #9
Thanks, guys!
I'm very happy that so many kind people help me.
I've learned a lot from you, THANKS!
Yet I still have two questions:
1. malloc(10000 * sizeof *bit);
^^^^^^^^^^^^
sizeof *bit what's this, can sizeof be used like this? wow,
I can not find this expression in all of my C books.
where can I find some reference to this?
I think sizeof is a function that calculate a type's size, so it
should be used with ( ),
and the * between "sizeof" and "bit" is a pointer or a multiply? I'm
really confused.

2. I once used memset like this, and it looked like works:
memset(semi,-1,sizeof(float)*16);
memset(final,-1,sizeof(float)*16);
memset(cup,-1,sizeof(float)*16);
printf("%f %f\n",semi[0],final[15]);

Output: -1.#QNAN0 -1.#QNAN0
It seemed that it was "-1" and I omitted the topic I just asked.
Now the question is "-1.#QNAN0" means what?
what is the #QNAN0?

Thank you for your patience and time!

Dec 4 '05 #10
Alex Fraser wrote:
AFAIK you can't portably set them to zero either, except possibly the
fixed-size ones added in C99 (uint32_t etc).


For character sets, a byte with all bits zero,
is a valid null character.

--
pete
Dec 4 '05 #11
On 4 Dec 2005 04:57:16 -0800, in comp.lang.c , "Frederick Ding"
<di*******@gmail.com> wrote:
Thanks, guys!
I'm very happy that so many kind people help me.
I've learned a lot from you, THANKS!
Yet I still have two questions:
1. malloc(10000 * sizeof *bit);
^^^^^^^^^^^^
sizeof *bit what's this, can sizeof be used like this?
sizeof is an operator, not a function. Its operand must be either a
type or an object. If the operand is an object, it doesn't need the
parens.
where can I find some reference to this?
The ISO C standard
6.5.3.4 The sizeof operator
Constraints
1 The sizeof operator shall not be applied to an expression that has
function type or an incomplete type, to the parenthesized name of such
a type, or to an expression that designates a bit-field member.
Semantics
2 The sizeof operator yields the size (in bytes) of its operand, which
may be an expression or the parenthesized name of a type.
I think sizeof is a function that calculate a type's size, so it
should be used with ( ),
No, its an operator
and the * between "sizeof" and "bit" is a pointer or a multiply?
No, its the indirection operator, same as in
int *bit;
2. I once used memset like this, and it looked like works:
memset(semi,-1,sizeof(float)*16);

Output: -1.#QNAN0 -1.#QNAN0
It seemed that it was "-1" and I omitted the topic I just asked.
Now the question is "-1.#QNAN0" means what?


it means your number is Not A Number. Clearly setting all bytes of a
float to -1 on your system causes the float to be a non-number.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 4 '05 #12
Frederick Ding a écrit :
Thanks, guys!
I'm very happy that so many kind people help me.
I've learned a lot from you, THANKS!
Yet I still have two questions:
1. malloc(10000 * sizeof *bit);
^^^^^^^^^^^^
sizeof *bit what's this, can sizeof be used like this? wow,
I can not find this expression in all of my C books.
It's a short way for sizeof p[0] that can be written *(p + 0), hence
*(p) hence finally *p.

It means 'the size of the first element of the pointed array'.
where can I find some reference to this?
Pointer arithmetics.
I think sizeof is a function that calculate a type's size, so it
Nope. sizeof is a unary operator. It works like this :

size_t size = sizeof object
size_t size = sizeof (type)
should be used with ( ),
It depends on the context. Note that an excess of parenthesis is
harmless (kinda belt and suspensers strategy !).
and the * between "sizeof" and "bit" is a pointer or a multiply?
None of them. It's the indirection operator (or dereference operator).
2. I once used memset like this, and it looked like works:
memset(semi,-1,sizeof(float)*16);
Don't use memset() on floating points. The result is implementation
dependent or more likely undefined.
memset(final,-1,sizeof(float)*16);
memset(cup,-1,sizeof(float)*16);
printf("%f %f\n",semi[0],final[15]);

Output: -1.#QNAN0 -1.#QNAN0
It seemed that it was "-1" and I omitted the topic I just asked.
Now the question is "-1.#QNAN0" means what?
what is the #QNAN0?


NAN means Not A Number. IOW, the internal format is undefined. Once
again, don't to that. What did you intent to do ?

--
A+

Emmanuel Delahaye
Dec 4 '05 #13
On Sun, 04 Dec 2005 14:51:21 +0100, in comp.lang.c , Emmanuel Delahaye
<em***@YOURBRAnoos.fr> wrote:
Frederick Ding a écrit :
memset(final,-1,sizeof(float)*16); Output: -1.#QNAN0 -1.#QNAN0
NAN means Not A Number. IOW, the internal format is undefined.


See for example:
http://stevehollasch.com/cgindex/coding/ieeefloat.html
if you examine the bitpattern your memset created, and compare it to
the table near the bottom, all will be revealed.
Once again, don't to that. What did you intent to do ?


I imagine he wante to set all his floats to value -1. To the OP:
memset does /exactly/ what it says on the tin - sets n bytes of memory
to value m. It does NOT set the value of the variable to n.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 4 '05 #14
"Malcolm" <re*******@btinternet.com> wrote in message
news:dm*********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com...
"Alex Fraser" <me@privacy.net> wrote
It sets every byte to a given value. The only practical use, really,
is to set memory to zero, unless, as you say, you happen to want a
string of asterisks or something.
You cannot set integers to a non-zero value.


AFAIK you can't portably set them to zero either, except possibly the
fixed-size ones added in C99 (uint32_t etc).


int array[100];

memset(array, 0, 100 * sizeof(int));

is guaranteed to produce an array to 100 integers of value 0, on an ANSI
system.


"All bits zero" implies "all padding bits zero" and I don't see why that
couldn't be a trap representation for int.

Alex
Dec 4 '05 #15
"pete" <pf*****@mindspring.com> wrote in message
news:43***********@mindspring.com...
Alex Fraser wrote:
AFAIK you can't portably set [integers] to zero [with memset] either,
except possibly the fixed-size ones added in C99 (uint32_t etc).


For character sets, a byte with all bits zero,
is a valid null character.


Noted.

Alex
Dec 4 '05 #16
"Alex Fraser" <me@privacy.net> writes:
"Malcolm" <re*******@btinternet.com> wrote in message
news:dm*********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com...
"Alex Fraser" <me@privacy.net> wrote
>> It sets every byte to a given value. The only practical use, really,
>> is to set memory to zero, unless, as you say, you happen to want a
>> string of asterisks or something.
>> You cannot set integers to a non-zero value.
>
> AFAIK you can't portably set them to zero either, except possibly the
> fixed-size ones added in C99 (uint32_t etc).


int array[100];

memset(array, 0, 100 * sizeof(int));

is guaranteed to produce an array to 100 integers of value 0, on an ANSI
system.


"All bits zero" implies "all padding bits zero" and I don't see why that
couldn't be a trap representation for int.


The response to Defect Report #263 says:

For any integer type, the object representation where all the bits
are zero shall be a representation of the value zero in that type.

This is published in Technical Corrigendum 2, and appears in n1124
(which includes the C99 standard with TC1 and TC2 merged in).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 4 '05 #17
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"Alex Fraser" <me@privacy.net> writes:
"Malcolm" <re*******@btinternet.com> wrote in message
news:dm*********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com... [snip]
memset(array, 0, 100 * sizeof(int));

is guaranteed to produce an array to 100 integers of value 0, on an
ANSI system.


"All bits zero" implies "all padding bits zero" and I don't see why
that couldn't be a trap representation for int.


The response to Defect Report #263 says:

For any integer type, the object representation where all the bits
are zero shall be a representation of the value zero in that type.

This is published in Technical Corrigendum 2, and appears in n1124
(which includes the C99 standard with TC1 and TC2 merged in).


Thank you.

Alex
Dec 4 '05 #18

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

Similar topics

4
by: J. Campbell | last post by:
From reading this forum, it is my understanding that C++ doesn't require the compiler to keep code that does not manifest itself in any way to the user. For example, in the following: { for(int...
9
by: Magix | last post by:
Hi, Let say I have: char szBuffer=""; 1. Which one is the better option to reset the buffer ? and why? strcpy(szBuffer,""); memset(szBuffer,'\0',sizeof(szBuffer)); OR
26
by: 69dbb24b2db3daad932c457cccfd6 | last post by:
Hello, I have to initialize all elements of a very big float point array to zero. It seems memset(a, 0, len) is faster than a simple loop. I just want to know whether it is safe to do so, since I...
14
by: Samuel R. Neff | last post by:
Why would you cast two strings to objects to compare them? I saw code in an MS sample on MSDN and don't get it. if ( (object)name == (object)attr.name ) { both "name" and "attr.name" are...
21
by: jacob navia | last post by:
Many compilers check printf for errors, lcc-win32 too. But there are other functions that would be worth to check, specially memset. Memset is used mainly to clear a memory zone, receiving a...
27
by: volunteers | last post by:
I met a question about memset and have no idea right now. Could anybody give a clue? Thanks memset is sometimes used to initialize data in a constructor like the example below. What is the...
22
by: silversurfer2025 | last post by:
Hello everybdy, I am a little confused for the following reason: In my code I used a simple for-loop in order to initialize a 2D-array of floats to zero. Because of efficiency reasons, I changed...
4
by: nass | last post by:
hello everyone, i have a bit of problem reading char * strings from a buffer (a shared memory, pointed to by 'file_memory'). basically i have a structure in memory 'ShMem' that can be accessed by...
20
by: merrittr | last post by:
I need some C advice I want to read in string commands from a user when the user enters a \n I want to push it on the stac. Then at some point , if the user enters the word print pop off and print...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.