pointers

R

RoSsIaCrIiLoIA

If sizeof(unsigned)=4 is this allowed?

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

int main(void)
{unsigned *i;
i = malloc(1);
return 0;
}

and this

int main(void)
{unsigned *i;
i = malloc(1);
*i=98;
return 0;
}
 
E

Emmanuel Delahaye

RoSsIaCrIiLoIA wrote on 28/07/04 :
If sizeof(unsigned)=4 is this allowed?

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

int main(void)
{unsigned *i;
i = malloc(1);

Yes, as far as you don't use 'i'. (Is it useful is another story).
return 0;
}

and this

int main(void)
{unsigned *i;
i = malloc(1);
*i=98;

No. Using 'i' invokes an undefined behaviour.
return 0;
}


Two more things : malloc() could fail, and you are supposed to free the
allocated memory...
 
F

Fred L. Kleinschmidt

RoSsIaCrIiLoIA said:
If sizeof(unsigned)=4 is this allowed?

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

int main(void)
{unsigned *i;
i = malloc(1);
return 0;
}

and this

int main(void)
{unsigned *i;
i = malloc(1);
*i=98;
return 0;
}

Why bother? Why not just use
i = malloc(sizeof(*i));
This is the same speed and much more useful - it works on all platforms,
i.e., when sizeof(unsigned) is 4 or 8 or anything else, and you can
change the type later and not worry about haviong to change all of the
malloc's.
 
K

Keith Thompson

Emmanuel Delahaye said:
RoSsIaCrIiLoIA wrote on 28/07/04 :

Yes, as far as you don't use 'i'. (Is it useful is another story).


No. Using 'i' invokes an undefined behaviour.
[...]

Using 'i' (e.g., by comparing it to NULL) should be ok; using *i, as
the quoted code fragment does, invokes undefined behavior.
 
R

RoSsIaCrIiLoIA

If sizeof(unsigned)=4 is this allowed?

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

int main(void)
{unsigned *i;
i = malloc(1); free(i);
return 0;
}

and this

int main(void)
{unsigned *i;
i = malloc(1);
*i=98; free(i);
return 0;
}
 

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

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top