473,472 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

struct stat *stbuf seg fault

I am new to c and not yet sure of the boundary between c and it's
implementations. So please redirect me if this should be asked elsewhere.

I am working on a function to determine if a directory exists. The idea
comes from a snippet I found in a samba source file.

bool dirExist(char *dname)
{
struct stat *stbuf;
//stbuf = (struct stat*)malloc(sizeof(struct stat));
bool ret;

if (stat(dname,stbuf) != 0)
return(False);

ret = S_ISDIR(stbuf->st_mode);
if(!ret)
errno = ENOTDIR;
printf("%s\n",ret);
return ret;
}

It seems to agree with page 180 of K&R2.

When passed a none existant directory name, it correctly reports a failure.
Yet, when passed a existant dir it segfaults at

stat(dname,stbuf)

Mallocing stbuf was just something I have been trying--didn't fix anything.

Thanks
Dave Farning




Nov 14 '05 #1
10 5237

I took a literary license and did some critiquing(sp?) of the code.

The direct answer to your question is marked.
bool dirExist(char *dname)
{
struct stat *stbuf;
declaring the struct in this manner will *not* make space on the stack
for the variable. Another way to do this (if you don't like doing
dynamic memory management for structs you know you'll need but don't want to
deal with the &'s all over the place) is:

struct stat _stbuf;
struct stat *stbuf = &_stbuf;

Either the program overflows the stack (and you should have a routine
registered to handle this event) or it works.

I also feel it's a bad idea to declare variables w/o initializing them because
a comparison to NULL later on might or might not reveal it as a useless
pointer. Typically, NULL is 0, and things are *magically* zero out of random
luck, but that's a combination of implementation definitions and luck.

---------------->ANSWER<--------------

The way you have it done as is, space is never being allocated for the buffer.
Consequently when the OS tries to find the file and fails, things go as
planned, but when it succeeds in finding the file, it tries to write to a junk
pointer, and thus segfaults.
//stbuf = (struct stat*)malloc(sizeof(struct stat)); i'm pretty sure // is illegal in ansi 89, but ok in 99

casting the return value of malloc is *bad*. Doing that will cause the
compiler not to complain that you forgot to include stdlib.
bool ret; if (stat(dname,stbuf) != 0)
return(False); ret = S_ISDIR(stbuf->st_mode);
if(!ret)
errno = ENOTDIR;
printf("%s\n",ret);
return ret;
}
I'm not sure what editor you're using, but i'm pretty sure that industry
standard is two spaces, and a naming convention of lower case and _'s instead
of mixed case.
Mallocing stbuf was just something I have been trying--didn't fix anything.


Not really sure. I tried test code with the following results:

my way: worked
malloc: worked
shown: segfaulted

hth

--
Harrison Caudill | .^ www.hypersphere.org
Computer Science & Physics Double Major | | Me*Me=1
Georgia Institute of Technology | v' I'm just a normal guy
Nov 14 '05 #2
Charles Harrison Caudill wrote:

I took a literary license and did some critiquing(sp?) of the code.

The direct answer to your question is marked.
bool dirExist(char *dname)
{
struct stat *stbuf;


declaring the struct in this manner will *not* make space on the stack
for the variable. Another way to do this (if you don't like doing
dynamic memory management for structs you know you'll need but don't want
to deal with the &'s all over the place) is:

struct stat _stbuf;
struct stat *stbuf = &_stbuf;

Either the program overflows the stack (and you should have a routine
registered to handle this event) or it works.

I also feel it's a bad idea to declare variables w/o initializing them
because a comparison to NULL later on might or might not reveal it as a
useless
pointer. Typically, NULL is 0, and things are *magically* zero out of
random luck, but that's a combination of implementation definitions and
luck.

---------------->ANSWER<--------------

The way you have it done as is, space is never being allocated for the
buffer. Consequently when the OS tries to find the file and fails, things
go as planned, but when it succeeds in finding the file, it tries to write
to a junk pointer, and thus segfaults.
//stbuf = (struct stat*)malloc(sizeof(struct stat));

i'm pretty sure // is illegal in ansi 89, but ok in 99

casting the return value of malloc is *bad*. Doing that will cause the
compiler not to complain that you forgot to include stdlib.
bool ret;

if (stat(dname,stbuf) != 0)
return(False);

ret = S_ISDIR(stbuf->st_mode);
if(!ret)
errno = ENOTDIR;
printf("%s\n",ret);
return ret;
}


I'm not sure what editor you're using, but i'm pretty sure that industry
standard is two spaces, and a naming convention of lower case and _'s
instead of mixed case.


Thanks, I'm coming from a world mostly of java, python, and bash. Camel
case and tab(4) were pretty much the habit I got into. It is trully amazing
how many way there are to bite yourself in the butt with C--Not complaining
just grumping.

After removing the (struct stat*) cast it works like a charm. I thought
that it was important to cast pointers to the type of object that they
point to. Am I heading down a errorous path of thought.
Secondly, you mentioned are routine to handle stack overflows. Could you
point to more imformation on this.

Thanks
Dave Farning
Nov 14 '05 #3
>I am new to c and not yet sure of the boundary between c and it's
implementations. So please redirect me if this should be asked elsewhere.

I am working on a function to determine if a directory exists. The idea
comes from a snippet I found in a samba source file.

bool dirExist(char *dname)
{
struct stat *stbuf;
Here you have declared a pointer variable, but it isn't
initialized to point anywhere, so it might point at the Mars Rover
or it might point at your butt.
//stbuf = (struct stat*)malloc(sizeof(struct stat));
bool ret;

if (stat(dname,stbuf) != 0)
Here you are using an uninitialized pointer and passing it to
a function that expects to write data where the pointer is pointing.
Ouch! If that pointer is not pointing at your butt, YOU might be
the one who caused the problems with the Mars Rover.

Try declaring a struct stat and making stbuf point at it.
return(False);

ret = S_ISDIR(stbuf->st_mode);
if(!ret)
errno = ENOTDIR;
printf("%s\n",ret);
return ret;
}

It seems to agree with page 180 of K&R2.

When passed a none existant directory name, it correctly reports a failure.
Yet, when passed a existant dir it segfaults at

stat(dname,stbuf)


Where, exactly, do you think stbuf is pointing?
Why SHOULDN'T you get a smegmentation fault?

Gordon L. Burditt
Nov 14 '05 #4
Gordon Burditt wrote:
I am new to c and not yet sure of the boundary between c and it's
implementations. So please redirect me if this should be asked elsewhere.

I am working on a function to determine if a directory exists. The idea
comes from a snippet I found in a samba source file.

bool dirExist(char *dname)
{
struct stat *stbuf;


Here you have declared a pointer variable, but it isn't
initialized to point anywhere, so it might point at the Mars Rover
or it might point at your butt.
//stbuf = (struct stat*)malloc(sizeof(struct stat));
bool ret;

if (stat(dname,stbuf) != 0)


Here you are using an uninitialized pointer and passing it to
a function that expects to write data where the pointer is pointing.
Ouch! If that pointer is not pointing at your butt, YOU might be
the one who caused the problems with the Mars Rover.


I take offense to the mars rover comment--now that previous lander oops,
I'll admit too. That had nothing to do with a conversion error beween feet
and meters, rather it was due to a conversion error between pints and
liters at the local pub the night before I wrote the code to handle the
landing.

Dave Farning
Nov 14 '05 #5
On 23 Feb 2004 05:16:25 GMT, Charles Harrison Caudill
<ku*****@myrna.cc.gatech.edu> wrote in comp.lang.c:

I took a literary license and did some critiquing(sp?) of the code.

The direct answer to your question is marked.
bool dirExist(char *dname)
{
struct stat *stbuf;
declaring the struct in this manner will *not* make space on the stack


^^^^^

What stack? No stack is defined or required by the C standard.

The point is that the OP created an uninitialized pointer. Accessing
the value of an uninitialized pointer produces undefined behavior, not
just attempting to dereference it.
for the variable. Another way to do this (if you don't like doing
dynamic memory management for structs you know you'll need but don't want to
deal with the &'s all over the place) is:

struct stat _stbuf;
While in this case there is no harm, it is generally a bad idea to
create identifiers beginning with a leading underscore. There are
specific cases where it is not allowed, and it is easier not to do so
at all than to remember the rules.
struct stat *stbuf = &_stbuf;

Either the program overflows the stack (and you should have a routine
registered to handle this event) or it works.
The stack has nothing to do with it. As far as the C standard is
concerned, the program can crash when the uninitialized pointer value
is accessed to pass to the function. The function might never
execute, let alone return a result.
I also feel it's a bad idea to declare variables w/o initializing them because
a comparison to NULL later on might or might not reveal it as a useless
There are good cases to be made both for initializing and not
initializing variables when they are defined. There would be no point
at all in initializing a pointer which would be assigned the value
returned by a call to malloc(), for example.
pointer. Typically, NULL is 0, and things are *magically* zero out of random
luck, but that's a combination of implementation definitions and luck.
Actually, NULL is required to be either 0 or (void *)0, or an
expression equivalent to one or the other. A null pointer may not be
represented by the pattern all bits 0, however.

---------------->ANSWER<--------------

The way you have it done as is, space is never being allocated for the buffer.
Consequently when the OS tries to find the file and fails, things go as
planned, but when it succeeds in finding the file, it tries to write to a junk
pointer, and thus segfaults.
//stbuf = (struct stat*)malloc(sizeof(struct stat));

i'm pretty sure // is illegal in ansi 89, but ok in 99

casting the return value of malloc is *bad*. Doing that will cause the
compiler not to complain that you forgot to include stdlib.


Agreed.
bool ret;

if (stat(dname,stbuf) != 0)
return(False);

ret = S_ISDIR(stbuf->st_mode);
if(!ret)
errno = ENOTDIR;
printf("%s\n",ret);
return ret;
}


I'm not sure what editor you're using, but i'm pretty sure that industry
standard is two spaces, and a naming convention of lower case and _'s instead
of mixed case.


Neither two spaces nor any one particular naming convention is
"industry standard", for whatever unspecified industry you have in
mind.
Mallocing stbuf was just something I have been trying--didn't fix anything.


Not really sure. I tried test code with the following results:

my way: worked
malloc: worked
shown: segfaulted

hth


--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #6
David Farning wrote:

I am new to c and not yet sure of the boundary between c and it's
implementations. So please redirect me if this should be asked
elsewhere.


Google for N869 and download the text version. It is easily
searched in an editor or via grep (which you can't do with the
official version). If the function is not mentioned there, it is
non-standard. I think there is one exception, because N869 is
actually a draft.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #7
David Farning <df******@sbcglobal.net> scribbled the following:
Gordon Burditt wrote:
bool dirExist(char *dname)
{
struct stat *stbuf;
Here you have declared a pointer variable, but it isn't
initialized to point anywhere, so it might point at the Mars Rover
or it might point at your butt.
//stbuf = (struct stat*)malloc(sizeof(struct stat));
bool ret;

if (stat(dname,stbuf) != 0)


Here you are using an uninitialized pointer and passing it to
a function that expects to write data where the pointer is pointing.
Ouch! If that pointer is not pointing at your butt, YOU might be
the one who caused the problems with the Mars Rover.

I take offense to the mars rover comment--now that previous lander oops,
I'll admit too. That had nothing to do with a conversion error beween feet
and meters, rather it was due to a conversion error between pints and
liters at the local pub the night before I wrote the code to handle the
landing.


None of this would have happened if the US had finally adopted the
metric system like *every single other bloody country in the world*.
They *said* they'd adopt it way back in the 19th century, and how much
have they done about it?

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"It's time, it's time, it's time to dump the slime!"
- Dr. Dante
Nov 14 '05 #8
David Farning <df******@sbcglobal.net> wrote:
Charles Harrison Caudill wrote: Secondly, you mentioned are routine to handle stack overflows. Could you
point to more imformation on this.


We're venturing out of the realm of the language, but the OS will typically
send your process a signal (this works at least on *nix's). You can handle
that signal intelligently.

google->c signal

hth

--
Harrison Caudill | .^ www.hypersphere.org
Computer Science & Physics Double Major | | Me*Me=1
Georgia Institute of Technology | v' I'm just a normal guy
Nov 14 '05 #9

In article <yU*****************@newssvr26.news.prodigy.com> , David Farning <df******@sbcglobal.net> writes:
Charles Harrison Caudill wrote:
I'm not sure what editor you're using, but i'm pretty sure that industry
standard is two spaces, and a naming convention of lower case and _'s
instead of mixed case.


Thanks, I'm coming from a world mostly of java, python, and bash. Camel
case and tab(4) were pretty much the habit I got into. It is trully amazing
how many way there are to bite yourself in the butt with C--Not complaining
just grumping.


*I* am pretty sure that there is no "industry standard" for either
indentation or mixed-case versus underscores in identifiers in C.
My advice would be to worry about the important stuff and ignore style
recommendations that don't have an obvious justification.

--
Michael Wojcik mi************@microfocus.com

Ten or ten thousand, does it much signify, Helen, how we
date fantasmal events, London or Troy? -- Basil Bunting
Nov 14 '05 #10
mw*****@newsguy.com (Michael Wojcik) writes:
*I* am pretty sure that there is no "industry standard" for either
indentation or mixed-case versus underscores in identifiers in C.


Definitely not. A company that I work for
WritesIdentifiersLikeThis but the GNU project
writes_them_like_this. It's just a style choice.
--
Bite me! said C.
Nov 14 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Matthias Käppler | last post by:
Hi, I'm using a glibc system header <sys/stat.h> which defines a C struct 'stat'. Furthermore, I'm using the struct 'dirent', defined in <dirent.h>. Now, at one point in my code I'm holding an...
3
by: Steven T. Hatton | last post by:
I found the following two statements in the file linked below: struct stat st; stat(fileName.c_str(), &st); http://websvn.kde.org/branches/work/kdevelop4-parser/main.cpp?rev=420247&view=markup...
19
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at...
11
by: J Wang | last post by:
dear, I debug the program recently as follows. #include <sys/stat.h> int main(int argc, char *argv) { struct stat buf;
0
by: ccfq | last post by:
I have a problem with GCC and C. (under Windows XP, CPU 32-bit Athlon XP, gcc version 3.4.5, mingw special) Is there some simple way to return the size of a large file (2GB+) without opening it?...
8
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I heard when define a struct, it is important to make the size of the struct memory aligned. For example, struct foo
3
by: Magesh | last post by:
How date-time attributes of a file are represented in the structure "struct stat"? Coz as I noted they found to be unsigned integers and I donno how they are interpreted as date & time in the...
2
by: Rolf =?UTF-8?B?S3LDvGdlcg==?= | last post by:
Hi I´m about learning C/C++ and after covering the language basics I´m now heading for my first "real" application where I need to use the POSIX stuff for directory operations. Here´s my...
3
by: Anna | last post by:
Could you please help me? I got a segmentation fault message while trying to assign a pointer = pointer like this: bufferlist=(buffer_t*)buffernew; What's the error by doing this? Here is the...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.