Urgent C Questions

R

Richard Heathfield

Chris Hills said:

At the time C++ was a superset of C.

C++ has never been a superset of C. If it were, all C programs would be C++
programs, which is clearly not the case.
 
P

Philip Potter

Chris said:
But starting with

void main ()

which is not strictly conforming for a hosted environment is probably
going to be accepted by most compilers.

On what do you base this claim? How many compilers have you tried?

And even if it's accepted by most compilers, it's still not accepted by
all, and may not be accepted by future versions of compilers which
accept it today.
I would expect an adult to read it as a main with no parameters or
return. Not produce the sort of childish reaction it got.

It doesn't matter what you expect an adult to read this as; the fact is
that a C implementation is not required to deal with it. Several do not
like it at all.

Phil
 
C

CBFalconer

Hans said:
1. in the prg bellow what vars are stored on stack, heap, data segment?

int i;
void main() {
int j;
int *k = (void *)malloc(1);
}

(I think j and k are on stack, but where is i?)

Nowhere. I count at least 4 (possibly 3 on C99) errors.
2. how to find sizeof variable w/o using sizeof command?

(no clue)

Not possible for general variables. char is size 1.
3. what is the o/p of this prg?

void main() {
int x = 5;
x = x++;
printf("x=%i", x);
}

(I think it shoulld be printing 5 but it prints 6!)
ps: I am using QuickC 2.0
pps: Is very urgent!

Undefined behaviour, besides the errors. ANY result is possible.
 
C

CBFalconer

Chris said:
.... snip ...


Possibly but I think it is far more likely they were not there to
save typing. In most programming books for example K&R 2nd ed
main is

main ()

Not if you have the intelligence to apply the published errata.
 
J

J. J. Farrell

Chris said:
...



It is valid C... for reasons of brevity the headers were not included.

I doubt it. Casting the result of malloc() to a <void *> before
assigning it to an <int *> gives off the classic smell of someone
throwing in casts to suppress warnings. Including the header would
admittedly have been a little less brief, but would at least be correct
and slightly reduce the impression that the instructor is clueless.
 
A

andreyvul

1. in the prg bellow what vars are stored on stack, heap, data segment?
Heap: malloc()ed memory
Stack: local variables
Data Segment: No clue (haven't done 16-bit x86 asm in a *long* time)
int i; On the outermost stack frame.
void main()
A return type of void works for main(); however, a non-int return type
for main is *not* recommended as int can potentially cause
segmentation faults and other problems.
{
int j; main()'s stack frame.
int *k = (void *)malloc(1);
k is stored in main()'s stack frame. It contains an address to heap
memory.
i.e., k is on the stack; *k is on the heap.
Furthermore, I think you meant to type:
int *k = (int *)malloc(1 * sizeof(int));
Big difference, for the following reasons:
1) malloc()'s return type is void *, making (void *)malloc()
redundant.
I think you meant (int *)malloc() so that malloc() returns int *.
2) malloc()'s argument is the size of memory *in bytes* to allocate.
malloc(1) allocates 1 byte, malloc(1 * sizeof(int)) allocates memory
for 1 int; the size in bytes allocated being sizeof(int). Do *not* do
sizeof(void) *at all*, as this is undefined (for good reasons).
You could also use (element type *)calloc(number of elements,
sizeof(element type)).
Or create a (preprocessor) macro like this:
#define mymalloc(n, type) (type *)malloc(n * sizeof(type))
and replace "int * i = (int *)malloc(n * sizeof(int))"
with "int * i = mymalloc(n, int);"
2. how to find sizeof variable w/o using sizeof command?
sizeof is a compiler (not preprocessor) macro. During compilation, the
compiler replaces sizeof(foo) with a number equal to the number of
bytes 1 foo takes up in memory. This is why malloc() and realloc()
*must* have "* sizeof(type)" in the size argument for them to perform
as expected.
Example (assume sizeof(int) == 2):

int * i = (int *)malloc(sizeof(int));

is equal to
int * i = (int *)malloc(2);
3. what is the o/p of this prg?

void main()
{
int x = 5;
x = x++;
printf("x=%i", x);
}
x = x++ is undefined, but judging on how ++ works, I think the program
expands it to something like this (asm in comments):
x = x; /* MOV X, X */
x++; /* INC X */
The program in asm:
..data
szPrintfFormat db "x=%i", 0
..text
start:
main:
MOV [SP - 4], 5 /* int x = 5 */
MOV [SP - 4], [SP - 4] /* x = x */
INC [SP - 4] /* x++ */
PUSH [SP - 4] /* push x on calling stack */
PUSH ADDR szPrintfFormat /* push address of null-
terminated string szPrintfFormat onto calling stack */
CALL printf
XOR AX, AX /* RET uses register AX as return value; XORing
it will set it to 0 */
RET /* return */
end main
int 0x23 /* I think this is the return-to-DOS interrupt */
end start
ps: I am using QuickC 2.0
You're using DOS. That's a bit of a help - it lets me type out valid,
working asm to show exactly how
pps: Is very urgent!
Sounds like a homework question. I explained it to the best (read most
verbose) of my abilities.
 
H

Hans Schneider

Jack said:
On Tue, 15 Jan 2008 03:41:56 +0100 (CET), Hans Schneider

For it to be a C question, urgent or not, it would have to be about
valid C code.


The line above generates undefined behavior, not valid C code.

The line above generates undefined behavior, not valid C code.

I didn't write this code, but what is wrong about it?
In 'C: the complete reference' all prgs start like that.
The line above generates undefined behavior, not valid C code.

Is x++ not the same as x=x+1?
Since there is no prototype for printf() in scope, this causes
undefined behavior, not valid C code.

QuickC didn't complain.
lcc-win32 prints lots of warnings.
Warning test.c: 3 old-style function definition for 'main'
Warning test.c: 3 missing prototype for 'main'
Warning test.c: 3 'void main()' is a non-ANSI definition
Warning test.c: 6 missing prototype for printf
Warning test.c: 6 Missing prototype for 'printf'
0 errors, 5 warnings

What do they mean?
Why are there 2 warnings on line 6?
I think it should print, "This code was written by an idiot!".

With MS QuickC and GCC it prints 6.
With lcc-win32 it prints 5.
But gcc says 'operation on x may be undefined'.
I'll have to investigate why.
Sorry, non of these is a question about the C language. If you are in
an actual C programming course, and your instructor asked these
questions for a homework assignment, do the following:

1. Immediately drop the class.

I can't!
It is required for an advanced class.
2. Complain to the school administration about the unqualified
instructor and erroneous material.

I don't think that's gonna work.
He is a cousin of the principal.
 
A

andreyvul

Jack Klein schrieb:







I didn't write this code, but what is wrong about it?
In 'C: the complete reference' all prgs start like that.



Is x++ not the same as x=x+1?
Only when x++ is defined, such as
((int *)a)[x++] = y;
a[x++] = b[y++];
x++;
But not
x = x++;
a[x] = a[x++];
a[x++] = b[x++];
See comp.lang.c FAQ, Questions 3.1, 3.2, and 3.9
link:
(3.1) http://c-faq.com/expr/evalorder1.html
(3.2) http://c-faq.com/expr/evalorder2.html
(3.9) http://c-faq.com/expr/evalorder4.html
QuickC didn't complain.
Mental note: QuickC is a retarded compiler.
But now you have a reason for bad code: Microsoft's C compiler said it
was fine. :p
But seriously, Visual C++ .NET onwards has full C89 support (stdint is
C99) and whines about these errors. It whines more about deprecated
functions in stdio, stdlib, string, and others.
lcc-win32 prints lots of warnings.
*GOOD*
lcc is standards-compliant and whines for good reasons.
Warning test.c: 3 old-style function definition for 'main'
Warning test.c: 3 missing prototype for 'main'
Methinks ambiguous prototype: main(void) or main(int, char **)?
I have a habit of main returning int and having int, char ** as
parameters. It's a good habit that avoids warnings.
Warning test.c: 3 'void main()' is a non-ANSI definition Non-int return type.
Warning test.c: 6 missing prototype for printf
Warning test.c: 6 Missing prototype for 'printf'
Missing said:
0 errors, 5 warnings

What do they mean?
Why are there 2 warnings on line 6?
I think it should print, "This code was written by an idiot!".

With MS QuickC and GCC it prints 6.
With lcc-win32 it prints 5. Which one prints 42?[1]
But gcc says 'operation on x may be undefined'.
I'll have to investigate why.
Read the links on the C FAQ that I posted earlier.
x = x++ is undefined. You cannot assume it is either 5 or 6. I think
that there is a compiler that converts "x = x++" to "x = 42"[1]
because neither make sense.
I can't!
It is required for an advanced class.
Advanced? WTF!?!
I'm guessing he has no clue what a linked list is; am I right?
I don't think that's gonna work.
He is a cousin of the principal.
You're screwed then :(

[1] Yes that was a Hitchhiker's joke.
 
J

Jack Klein

The post from Jack is a classic example of why c.l.c is getting such a
bad name for itself.

However that said, this is nto a place to get last minute homework done.




It is valid C... just not strictly conforming .

No, it is not valid C. Undefined behavior renders it invalid.
How does it's undefined behaviour impinge on the question asked?


It is valid C... for reasons of brevity the headers were not included.

Where in the OP's post did it state that? What evidence do you have
that this is true?

There are implementations, even those where int and pointer happen to
be the same size, that this code will fail miserably, because pointers
and ints are returned in different manners.
However your pedantry is irrelevant to answering the question at hand.

No, it is not. Once there is "void main()" there are no requirements
at all on the program, because it is not C. And if malloc() is called
without a prototype in scope, and I see no evidence that there is a
prototype in scope, that is just more undefined behavior.

Not to mention the fact that "the question at hand" has no answer in
the C language, which does not define a "stack". Nor does it specify
where an external object like 'i' resides.
Yes it is. Unless you are an internationally obtuse pedant. Try
communicating with humans once in a while

I have in no way attempted to deny that the OP is human, despite the
egregious homework post. In fact, I am rather certain that the OP is,
indeed, human. While bots can generate incredibly varied text these
days, I don't think there is one quite up to generating a "do my
homework" post like this.
It is valid C... just not strictly conforming .

How does it's undefined behaviour impinge on the question asked?

Once a program generates undefined behavior, the C language no longer
imposes any requirements on it. Period.

Are you actually the Chris Hills of PhaedruS SystemS, Hitex, MISRA,
and the BSI/ISO C panel, or a troll using his email address on your
posts?

Aren't you aware of MISRA-C 2004 12.2 (required)?

Aren't you aware of 6.3 in ISO 9899:1990 and the identical wording in
ISO 9899:1999:

"Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an
expression."

Since this code modifies the value of the object 'x' twice without an
intervening sequence point, it violate a "shall" clause outside of a
constraints section, which, of course, produces undefined behavior.

Again, apparently, you have access to information that we mere
mortals, who only read what the OP posted, are denied. Given the
caliber of the post, I choose to assume that the headers are not
included.
The headers were omitted in this code fragment for brevity.
Assuming the headers were there what is the problem?

Since the previous statement modified an object twice without an
intervening sequence point, whether this printf() call executes is
immaterial from a C language point of view, let alone what output it
might happen to produce, if any, if it does execute.

What do you think the output will be? And why?
No the OP is ignorant. You are just insulting and not much of a person.
Try communicating with people occasionally.

I do not assume that the OP wrote the code. In fact I think it is
more likely that it was given to him as a homework assignment. And
that's the sad part of it, that he is dealing with an instructor, or
perhaps a tutorial web site, that considers these legitimate
questions, and they are not.
They are but you don't have the breath of intelligence or common sense
to understand. You must be a liability if you have to work with humans,

Oh, I'm sad, for now you have turned to personal insult. And
incorrect, because most of my coworkers are human, and the rest almost
so. ;)
Ignore Jack.


Keep going but do your own homework and don't do it at the last
minute.

As a member of several standards bodies and a certified engineer, I am
appalled at the fact that you are condoning the teaching of blatantly
incorrect material.
But do remember as he can actually communicate with his human class he
is probably going to be better than Jack.

Are you the real Chris Hills?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
 
P

ppi

Is x++ not the same as x=x+1?

yep, the thing is that you are trying to assign it back to x. What is
the big deal ?

y = x++; // well behaved: work has you expect

so why is it undefined behavior when x= x++ ?

y = x++ can be decomposed in the following logical steps by your
compiler:

1) save the value of x to a temp value z
2a) increment value of x by one / assign x with value x + 1
2b) assign y with z
(implementor may be in the mood to use: registers ? indirect
adressing ? other stuff?)

step 2a and 2b can occur in any given order as far as the compiler is
concerned - at the end of the assignment both will have occured, that
is the guaranty we do have.

when writing x = x++ step 2a and 2b can occur at any time and as such
2 different results are possible. Which one is the correct one ?
The standard flagged this as undefined behavior - the implementor
(compiler writer) is the one that choose how to implement it (given
that he can and actually has a choice).
Since most of them are nice people, you just got lucky that they
didn't burn your computer down or formated your disk as a fat16 file-
system when you tried to run the program (lucky you :) ) - supposing
that you were able to get a binary to run.
QuickC didn't complain.
lcc-win32 prints lots of warnings.
Warning test.c: 3 old-style function definition for 'main'
Warning test.c: 3 missing prototype for 'main'
Warning test.c: 3 'void main()' is a non-ANSI definition
Warning test.c: 6 missing prototype for printf
Warning test.c: 6 Missing prototype for 'printf'
0 errors, 5 warnings

http://www.amazon.com/Programming-Language-Prentice-Hall-Software/dp/0131103628

That is the best I can do. Note that this is only if you want to
actually learn something about this language (knowledge/understanding
is so overrated nowadays).

If you just want to get your homework done without actually
understanding what you are doing you may want to try:
http://www.google.ca/search?q=c+tutorial :)

If you keep on posting without doing at least that kind of research, I
am afraid you won't understand the replies we will give you.

cheers,
Paulo
 
R

Ravishankar S

Hans Schneider said:
1. in the prg bellow what vars are stored on stack, heap, data segment?

int i;

void main()
{
int j;
int *k = (void *)malloc(1);
}

(I think j and k are on stack, but where is i?)
the answers are specific to your environment. i take this risk of
displeasing the Std C gods to
give "inaccurate" answers:

i and k are on the "stack" (assuming the enviroment uses a stack like data
structure to maintain activation records)
what is pointed to by k (ie *k) is on the "heap" (if we assume that
environment allows us to call the place when malloc
reserves storage to be calledas "heap")

and i is on the "bss" segment (assume that the ".data" is always used by
compiler for initialized gobal and static variable and ".bss" is for
unitialized global and static) variable.

notice the number of assumptions. but nevertheless is true for some
environments (which is probably the case with QuickC).

2. how to find sizeof variable w/o using sizeof command?

(no clue)

I had seen a post which used pointer arithmetic. Its subject to correction
by the experts:
sizeof(i) == ((&i) + 1) - (&i))
Perhaps useful for your assignment
3. what is the o/p of this prg?

void main()
{
int x = 5;
x = x++;
printf("x=%i", x);
}

(I think it shoulld be printing 5 but it prints 6!)

ps: I am using QuickC 2.0

pps: Is very urgent!

Undefined behaviour.

Final Note: Why is the compiler called QuickC ? I think perhaps because it
allows you to quickly type any C program
without proper headers and declaration and yet produce some answer.
 
A

andreyvul

Final Note: Why is the compiler called QuickC ?
So that the programmer can *QUickl*ly*C* that Microsoft products are
standards-incompliant in the worst case. :p
 
C

CBFalconer

Hans said:
I didn't write this code, but what is wrong about it?
In 'C: the complete reference' all prgs start like that.

If that is the H Schildt (sp?) book, you are lucky. You have now
been advised that it is useless and stuffed full of errors, because
the author doesn't understand C. See if you can get some practical
use of it as a replacement for a log in the fireplace.
 
W

Walter Roberson

I had seen a post which used pointer arithmetic. Its subject to correction
by the experts:
sizeof(i) == ((&i) + 1) - (&i))
Perhaps useful for your assignment

The result of that would always be 1, for any variable of any type.
You missed a couple of casts.
 
R

Ravishankar S

Walter Roberson said:
The result of that would always be 1, for any variable of any type.
You missed a couple of casts.

oh yes. ((void*)((&i) + 1) - (void*)(&i)).but arithmetic on void pointers is
not defined i guess.
 
R

Richard Heathfield

andreyvul said:
So that the programmer can *QUickl*ly*C* that Microsoft products are
standards-incompliant in the worst case. :p

Discounting C99, conformance to which very few implementors have seriously
bothered to attempt, what conformance issues do you have with Microsoft's
series of C compilers? That is, in what way do you think they fail to
conform to C90?
 
J

Joachim Schmitz

Hans said:
I didn't write this code, but what is wrong about it?
In 'C: the complete reference' all prgs start like that.
One billions flies can't be wrong: dung tasts great

Bye, Jojo.
 
C

Chris Hills

Richard Heathfield said:
Chris Hills said:



C++ has never been a superset of C.

According to its author it was when he started.
If it were, all C programs would be C++
programs, which is clearly not the case.

Things move C++ was based on C89 since then noth C and C++ have moved
in different directions.

In the beginning C++ was a superset of C otherwise they could not have
used the C++ compiler for initial testing and then a C compiler for
final testing,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,880
Messages
2,569,944
Members
46,246
Latest member
RosalieMar

Latest Threads

Top