473,408 Members | 2,888 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,408 software developers and data experts.

Return of a string that fails

My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.

I tried to drop down some code (as follows) but it doesn't work.
Compiling is successfully, but print8bit() doesn't return anything.

Was wondering where I'm mistaking. Thanks in advance for your help.

/* code starts here */

char* print8bit (unsigned char n)
{
char s[9]; /* Allocate an array of 8+1 char */

int i, j; /* Counter variables */

for (j=7,i=0; j>=0,i<=7 ; j--,i++)
{
if(n & (1<<i))
s[j]='1';
else
s[j]='0';
}

s[8]='\0'; /* Marker of end of string */

return s; /* Return the first address of char array? */
}

int main(void)
{

char* str = print8bit(128); /* str[] now should be '1000000' */

printf("%d: %s", 128, str); /* on stdout is printed only '128:' */

return 0;
}

/* code ends here */
Jun 27 '08 #1
11 1236
On May 20, 1:52 pm, nembo kid <nembo@kidwrote:
My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.
HW questions, hmmmmm...
I tried to drop down some code (as follows) but it doesn't work.
Compiling is successfully, but print8bit() doesn't return anything.

Was wondering where I'm mistaking. Thanks in advance for your help.
You return a pointer to an object whose lifetime is over. That's
undefined behavior.
<snip code>
Jun 27 '08 #2
vi******@gmail.com ha scritto:
You return a pointer to an object whose lifetime is over. That's
undefined behavior.
Ok, found..,.that silly I am.

Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
heap I shouldn't have any issue....seems that the same happens with
linked list (that are allocated on the heap).

So either I'd use the qualificator 'static' to "keep on alive" s after
exiting from the function or pass its address as parameter (a pointer to
a pointer).

Both solutions are equivalent?

Thanks again.
Jun 27 '08 #3
On May 20, 2:12 pm, nembo kid <nembo@kidwrote:
vipps...@gmail.com ha scritto:
You return a pointer to an object whose lifetime is over. That's
undefined behavior.

Ok, found..,.that silly I am.

Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
heap I shouldn't have any issue....seems that the same happens with
linked list (that are allocated on the heap).

So either I'd use the qualificator 'static' to "keep on alive" s after
exiting from the function or pass its address as parameter (a pointer to
a pointer).

Both solutions are equivalent?
No, the second solution, assuming void f(unsigned char c, char **s)
will not work unless you assign *s a static array or a value from
malloc/calloc/realloc.
Here's the best solution:

void f(unsigned char c, char *s)

And write to s. You may assume that 's' is at least CHAR_BIT+1 long,
and the user of the function is responsible to make sure it is.
Jun 27 '08 #4
On May 20, 12:12*pm, nembo kid <nembo@kidwrote:
vipps...@gmail.com ha scritto:
You return a pointer to an object whose lifetime is over. That's
undefined behavior.

Ok, found..,.that silly I am.

Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
heap I shouldn't have any issue....seems that the same happens with
linked list (that are allocated on the heap).

So either I'd use the qualificator 'static' to "keep on alive" s after
exiting from the function or pass its address as parameter (a pointer to
a pointer).

Both solutions are equivalent?
Using 'static' is an instant fix.

But has the disadvantage that, if the caller doesn't use or copy the
value in s straightaway, the function can be called elsewhere and s
can be overwritten.
-- Bartc
Jun 27 '08 #5

"nembo kid" <nembo@kidschrieb im Newsbeitrag
news:48***********************@reader2.news.tin.it ...
My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.

I tried to drop down some code (as follows) but it doesn't work. Compiling
is successfully, but print8bit() doesn't return anything.

Was wondering where I'm mistaking. Thanks in advance for your help.

/* code starts here */
#include <limits.h/* for CHAR_BIT, portable */
#include <stdio.h/* for printf(), undefined behavoir otherwise */
>
char* print8bit (unsigned char n)
{
char s[9]; /* Allocate an array of 8+1 char */
static char s[CHAR_BIT+1]; /* Allocate an array of CHAR_BITS+1 char */
>
int i, j; /* Counter variables */

for (j=7,i=0; j>=0,i<=7 ; j--,i++)
for (j=CHAR_BIT,i=0; j>0,i<CHAR_BIT ; j--,i++)
{
if(n & (1<<i))
s[j]='1';
else
s[j]='0';
}

s[8]='\0'; /* Marker of end of string */
s[CHAR_BIT]='\0'; /* Marker of end of string */
>
return s; /* Return the first address of char array? */
}

int main(void)
{

char* str = print8bit(128); /* str[] now should be '1000000' */

printf("%d: %s", 128, str); /* on stdout is printed only '128:' */

return 0;
}

/* code ends here */
Bye, Jojo
Jun 27 '08 #6
nembo kid <nembo@kidwrote:
vi******@gmail.com ha scritto:
You return a pointer to an object whose lifetime is over. That's
undefined behavior.

Ok, found..,.that silly I am.

Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
heap I shouldn't have any issue....seems that the same happens with
linked list (that are allocated on the heap).
"Stack" and "heap" are deceptive terms. What matters is the duration of
the object you return, not where it is placed. You might want to read
questions 7.5a and 7.5b from the FAQ:
<http://c-faq.com/malloc/retaggr.htmland
<http://c-faq.com/malloc/retaggr2.html>.

Richard
Jun 27 '08 #7
Joachim Schmitz wrote:
"nembo kid" <nembo@kidschrieb im Newsbeitrag
news:48***********************@reader2.news.tin.it ...
>My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.
> int i, j; /* Counter variables */

for (j=7,i=0; j>=0,i<=7 ; j--,i++)
for (j=CHAR_BIT,i=0; j>0,i<CHAR_BIT ; j--,i++)
or simply

for (j=CHAR_BIT,i=0; i<CHAR_BIT ; j--,i++)

The expression j>=0 is evaluated and discarded. Most compilers will issue
a warning for this.

--
Thad
Jun 27 '08 #8
Thad Smith wrote:
Joachim Schmitz wrote:
>"nembo kid" <nembo@kidschrieb im Newsbeitrag
news:48***********************@reader2.news.tin.i t...
>>My homework is to make a simple function that, given a unsigned
char, should returns its bit string representation.
>> int i, j; /* Counter variables */

for (j=7,i=0; j>=0,i<=7 ; j--,i++)
for (j=CHAR_BIT,i=0; j>0,i<CHAR_BIT ; j--,i++)

or simply

for (j=CHAR_BIT,i=0; i<CHAR_BIT ; j--,i++)

The expression j>=0 is evaluated and discarded. Most compilers will
issue a warning for this.
True, copy'n'paste error on my side...

Bye, Jojo
Jun 27 '08 #9
vi******@gmail.com wrote:
>
On May 20, 1:52 pm, nembo kid <nembo@kidwrote:
My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.
HW questions, hmmmmm...
Well, (1) he says it's homework, right up front, and (2) he posts
his current code and asks for help on finding his error. Sounds like
someone who deserves help, which I see you have provided. I don't
think anyone here has a problem helping people with their homework.
It's the ones who come here asking us to _do_ their homework that
are the problem.

Finally, those who post with gender-neutral names will be refered to
as "he" until contradictory information is provided. :-)

[...]

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Jun 27 '08 #10
nembo kid wrote:
vi******@gmail.com ha scritto:
>You return a pointer to an object whose lifetime is over. That's
undefined behavior.

Ok, found..,.that silly I am.

Because 's[]' is allocated on the stack. But if I'd allocate s[] on the
heap I shouldn't have any issue....seems that the same happens with
linked list (that are allocated on the heap).

So either I'd use the qualificator 'static' to "keep on alive" s after
exiting from the function or pass its address as parameter (a pointer to
a pointer).

Both solutions are equivalent?
The first solution isn't reentrant, which means that if your program is
multi-threaded, two threads calling your function roughly at the same
time could contemporaneously write on the static buffer. What you would
get is garbage.

I would suggest to pass the address of a pre-allocated char array, or to
pass a pointer to a pointer to char and let your function dynamically
allocate it. The caller would then need to free it.

char *print8bit(unsigned char n, char **result)
{
if(!(*result = malloc(CHAR_BIT + 1)))
return (NULL);
/*
* put your things into *result[x]
*/
}
>
Thanks again.

--
Pietro Cerutti
Jun 27 '08 #11
Kenneth Brody ha scritto:
It's the ones who come here asking us to _do_ their homework that
are the problem.
Finally, those who post with gender-neutral names will be refered to
as "he" until contradictory information is provided. :-)

Sorry, but You are wrong.
Jun 27 '08 #12

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

Similar topics

11
by: Marcus Jacobs | last post by:
Dear Group I have written a file conversion program that uses strtof to convert text strings to floats. It works as I intended except for my error messages. It is my understanding that strtof...
59
by: Michael C | last post by:
eg void DoIt() { int i = FromString("1"); double d = FromString("1.1"); } int FromString(string SomeValue) {
3
by: Oberon | last post by:
How do I deal with this? I am getting an error for each get in the Game class (see code below). In the simplified example below I have reduced this to just 3 fields, one which can be NULL. I...
3
by: Bookreader | last post by:
Is it possible to return a code to Visual Basic when an Access reports completes successfully and a different code when a report fails? Thank you.
14
by: dcassar | last post by:
I have had a lively discussion with some coworkers and decided to get some general feedback on an issue that I could find very little guidance on. Why is it considered bad practice to define a...
7
by: Rudy | last post by:
Hello All! I have a value in a textbox(txbTableIDm.Text ) that I would like to use in a paremiter in a SP I wrote, and then have the select statement work off that parememter, retireive a...
1
by: BobbyJohn | last post by:
Hello.. I am attempting to load a Subform from a recordset. The recordsource is set to a string containing SQL using a query object. The Recordsource returns 0 rows in RecordSet, yet when the same...
11
by: MLH | last post by:
The following procedures found at http://ffdba.com/downloads/Send_Mail_With_Outlook_Express.htm are meant to work together in harmony to effect eMail sends via OE. The last procedure (FN SplitB)...
5
by: jimbrown | last post by:
This works in VS2008 for 32-bit projects but fails for 64-bit projects. How do I return a result that C# will interpret as a string? C# private static extern string getAString(); String...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
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...
0
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...

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.