On Sat, Mar 21, 1998 at 02:04:29AM -0500, Saad wrote:
> I'm experiencing a problem with a C program.  I am allocating two nodes
> dynamically and creating a linked list.  The problem is when I return from
> the function, it gives me a segmentation fault.  My code looks fine, and
> it runs fine under digital unix.  Do I have to do something different with
> linux when using dynamic memory?  I've attached my code if someone would
> look at it.  Thanks for the help.

>  <snip...>

> link read_file(void)
> {
>   char filename; FILE *ifp;

>  <snip...>

>   printf("%s", "Enter file name: ");
>   scanf("%s", &filename);

You are not allocating any RAM for storing the filename. You're
declaring a single character and using it to store an entire string.
So, in so doing you've trashed the stack such that the return address
(or other data on the stack which is needed at or immediately after
return-time) now points into never-never-land, hence the big BOOOOOOOOOM.
Change the declaration of filename from:

        char filename;
to:
        char filename[100];

for a minimally safe solution. To really do it right, allocate an array you 
THINK will be big enough, then use fgets() to read from the keyboard,
NOT scanf. Fgets allows you to put a limit on the number of characters
that can be input, whereas scanf (not to mention gets) does not.

Fred
-- 
---- Fred Smith -- [EMAIL PROTECTED] ----------------------------
  "For him who is able to keep you from falling and to present you before his 
 glorious presence without fault and with great joy--to the only God our Savior
 be glory, majesty, power and authority, through Jesus Christ our Lord, before
                     all ages, now and forevermore! Amen."
----------------------------- Jude 1:24,25 (niv) -----------------------------


-- 
  PLEASE read the Red Hat FAQ, Tips, Errata and the MAILING LIST ARCHIVES!
http://www.redhat.com/RedHat-FAQ /RedHat-Errata /RedHat-Tips /mailing-lists
         To unsubscribe: mail [EMAIL PROTECTED] with 
                       "unsubscribe" as the Subject.

Reply via email to