On November 19, 2009 18:53, in comp.lang.c, frank ()
wrote:
[snip]
> I tried to get the returns from malloc but hit a bump somewhere:
>
> dan@dan-desktop:~/source$ gcc -std=c99 -Wall -Wextra malloc1.c -o out
> malloc1.c: In function ‘main’:
> malloc1.c:25: warning: unused variable ‘c’
> dan@dan-desktop:~/source$ ./out
> Segmentation fault
> dan@dan-desktop:~/source$ cat malloc1.c
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> void bar( char **s )
Function bar accepts a pointer to a pointer-to-char, right?
> {
> *s = malloc( 10 );
Here, you take that pointer to a pointer-to char, find what it points to,
and change that value so that it now points to the data area you have
malloc()ed.
In other words,
Before the line,
s pointed to a pointer, and that pointer pointed somewher
After the line,
s still pointed to the same place, but the contents of that place have
been changed to now contain the value returned by malloc()
With me so far?
> }
>
> char *baz( void )
> {
> char *s = malloc( 10 );
>
> return s;
> }
>
>
> int
> main(void)
> {
> void bar ( char ** );
> char * baz ( void );
> char ** a;
Here, you allocate a as a pointer to pointer-to-char. But, you leave it
uninitialized; a doesn't point at anything in particular (it's value is
indeterminate).
> char * b;
> int c;
>
> bar ( a );
Now, you pass a, an unitialized pointer to bar(). Remember what bar() will
do; it will try to modify the area that this pointer points to.
But, this pointer has an indeterminate value; it /could/ point anywhere,
including outside of the space in which your program and it's data reside.
<off_topic>
Now, when a Unix process (that being the platform you are apparently
compiling and running on) tries to access memory outside of the bounds of
the process's memory map, Unix protects that memory, and sends a SIGSEGV
signal to the process. Uncaught, this SIGSEGV will cause the process to
abort, with a "Segmentation Violation" error message. That's what you got.
</off_topic>
The cure for your problem is to, prior to invoking function bar(),
*initialize* the pointer so that it points at a pointer-to-char.
Given your existing code, what you really wanted to do was...
a = &b;
bar ( a );
or, in shorter form
bar (&b);
> b = baz( );
> #if 0
> c = * b;
> strcpy(b, "qwerty");
> printf ("%s\n", b);
> #endif
>
>
> return 0;
> }
> // gcc -std=c99 -Wall -Wextra malloc1.c -o out
> dan@dan-desktop:~/source$
>
> One other thing. I just tried to man indent to find the usage for
> setting the tablength at 4, as pete had it for his code. How do you do
> that?
--
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
Me:
http://pitcher.digitalfreehold.ca/ | Just Linux:
http://justlinux.ca/
---------- Slackware - Because I know what I'm doing. ------