Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #105982
| From | Ian Collins <ian-news@hotmail.com> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: Two C code questions |
| Date | 2017-03-14 17:16 +1300 |
| Message-ID | <eip94fFhe9iU4@mid.individual.net> (permalink) |
| References | <oa7oru$rkf$1@dont-email.me> |
On 03/14/17 04:45 PM, MehdiAmini wrote:
> // Clang version 3.8.0
>
> // Question 1:
> #include <stdio.h>
> #include <stdlib.h>
> #include <inttypes.h>
>
> void my_alloc( void *, size_t );
>
> int main(void)
> {
> unsigned *u_ptr = NULL;
> //unsigned *u_ptr; // Why using this instead of above line causes
> core dump?
>
> my_alloc(u_ptr,sizeof(*u_ptr));
>
> free(u_ptr);
> return EXIT_SUCCESS;
> }
The answer to why it causes a crash is the value of u_ptr is garbage.
It is safe to pass NULL to free, but not garbage..
> void my_alloc( void *v_ptr, size_t size )
> {
> v_ptr = malloc(size);
> if( v_ptr == NULL )
> {
> fprintf(stderr,"Memory allocation failed.\n");
> exit(EXIT_FAILURE);
> }
>
> return ;
> }
The first parameter should b "void**", a pointer to a void pointer.
Otherwise all you are doing is assigning to the function parameter, with
is local to the function.
With the correct parameter type, use:
*v_ptr = malloc(size);
> // Question 2:
> #include <stdio.h>
> #include <stdlib.h>
> #include <inttypes.h>
>
> #define N 6
> //static const long N = 6; // Why using this instead of above line
> causes error?
>
> int main(void)
> {
> uint64_t ui[N] = {0};
C doesn't have a proper const, so you will be creating a variable length
array which cannot be initialised.
--
Ian
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Two C code questions MehdiAmini <atorrses@gmail.com> - 2017-03-14 07:15 +0330
Re: Two C code questions Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2017-03-13 22:13 -0600
Re: Two C code questions Ian Collins <ian-news@hotmail.com> - 2017-03-14 17:16 +1300
Re: Two C code questions Ike Naar <ike@iceland.freeshell.org> - 2017-03-14 07:20 +0000
Re: Two C code questions MehdiAmini <atorrses@gmail.com> - 2017-03-14 12:01 +0330
Re: Two C code questions Ike Naar <ike@iceland.freeshell.org> - 2017-03-14 19:23 +0000
Re: Two C code questions Keith Thompson <kst-u@mib.org> - 2017-03-14 12:40 -0700
Re: Two C code questions scott@slp53.sl.home (Scott Lurndal) - 2017-03-14 12:44 +0000
Re: Two C code questions Keith Thompson <kst-u@mib.org> - 2017-03-14 08:53 -0700
Re: Two C code questions MehdiAmini <atorrses@gmail.com> - 2017-03-15 14:05 +0330
Re: Two C code questions John Bode <jfbode1029@gmail.com> - 2017-03-14 10:38 -0700
Re: Two C code questions Keith Thompson <kst-u@mib.org> - 2017-03-14 11:49 -0700
Re: Two C code questions John Bode <jfbode1029@gmail.com> - 2017-03-14 14:14 -0700
csiph-web