:: [DNG] [OT] Re: Studying C as told.…
Pàgina inicial
Delete this message
Reply to this message
Autor: KatolaZ
Data:  
A: dng
Assumpte: [DNG] [OT] Re: Studying C as told. (For help)
On Thu, Jun 23, 2016 at 02:42:13AM +0200, Irrwahn wrote:

[cut]

>
> Actually, I think it in fact /still/ invokes undefined behavior,
> as it is only valid to cast from a pointer-to-T to a pointer to a
> compatible type (and back), or from a pointer-to-T to void pointer
> (or a pointer-to-unsigned-char[1]) and back to a type compatible
> with T.
>
> So, your casts to char* are at least fishy (since we cannot tell
> if char is signed or unsigned, as that is implementation defined),
> and the cast to float* is downright wrong. You only avoided the
> compiler barfing[2] at you by hiding the error behind explicit
> type casts. If you remove the bogus casts, even gcc coughs up
> appropriate diagnostics[2] about the incompatibility of the
> pointer types involved.
>


Thanks for your explanation :) Actually, my point was simply that the
language allows you to do whatever you want with allocated space that
you think is "an array of T". If I remove the explicit casts, the
compiler gives a few warning (incompatible pointer type) but still
compiles the code into an executable.

I am not saying that this is the way to proceed. Such warnings have to
be always resolved in any serious piece of code. But the language
allows you to do that, simply because there is no strong typing
whatsoever of any kind of either statically or dynamically allocated
memory. Consider the snippet (no malloc here...):

===
#include <stdio.h>
int main(){

    int a = 17;
    char *b;


    b = (char*)&a;
    b[2]=21;
    printf("a: %d\n", a);
    b[2]=0;
    printf("a: %d\n", a);
}
===


whose execution gives:

katolaz@akela:~/test$ ./pointer_wierd
a: 1376273
a: 17
katolaz@akela:~/test$

What is the type of the variable a? What is an array of "char"? Even
worse, this code will run smoothly on some architectures and give
segfault on other ones. And is still perfectly *legal* ANSI C :)

HND

KatolaZ

-- 
[ ~.,_  Enzo Nicosia aka KatolaZ - GLUGCT -- Freaknet Medialab  ]  
[     "+.  katolaz [at] freaknet.org --- katolaz [at] yahoo.it  ]
[       @)   http://kalos.mine.nu ---  Devuan GNU + Linux User  ]
[     @@)  http://maths.qmul.ac.uk/~vnicosia --  GPG: 0B5F062F  ] 
[ (@@@)  Twitter: @KatolaZ - skype: katolaz -- github: KatolaZ  ]