473,796 Members | 2,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

segfault w/ block, but not file scope

Hi.

In the snippet of code below, I'm trying to understand why when the

struct dirent ** namelist

is declared with "file" scope, I don't have a problem freeing the
allocated memory. But when the struct is declared in main (block scope)
it will segfault when passing namelist to freeFileNames() .

Since this seems to be just a matter of my understanding scope and
pointer parameter passing better, I only included what thought to be
relevant code. I'll happily provide compilable code if deemed necessary.

Please see commented lines:
struct dirent **namelist; /* file scope works */

int main(void)
{
/* struct dirent **namelist */ /* block scope doesn't work */
int n;

n = getFileNames(H5 DIR, namelist); /* included from mylib.h */
freeFileNames(n amelist, n); /* included from mylib.h */

return 0;
}
Thank you very much for your comments,
Dieter
Jan 6 '06
165 6914
Dieter wrote:
Hi.

In the snippet of code below, I'm trying to understand why when the

struct dirent ** namelist

is declared with "file" scope, I don't have a problem freeing the
allocated memory. But when the struct is declared in main (block scope)
it will segfault when passing namelist to freeFileNames() .

Since this seems to be just a matter of my understanding scope and
pointer parameter passing better, I only included what thought to be
relevant code. I'll happily provide compilable code if deemed necessary.

Please see commented lines:
struct dirent **namelist; /* file scope works */

int main(void)
{
/* struct dirent **namelist */ /* block scope doesn't work */
int n;

n = getFileNames(H5 DIR, namelist); /* included from mylib.h */
freeFileNames(n amelist, n); /* included from mylib.h */

return 0;
}
Thank you very much for your comments,
Dieter


My apologies to the regulars for an OT inclusion related to the question.
< This Thread Closed >
Thanks,
Dieter
Jan 6 '06 #11
Chris Torek wrote:
In article <SZ************ *************** ***@comcast.com >
Dieter <us**********@c omcast.net> wrote:
struct dirent **namelist; /* file scope works */

int main(void)
{
/* struct dirent **namelist */ /* block scope doesn't work */
int n;

n = getFileNames(H5 DIR, namelist); /* included from mylib.h */

This passes the *value* of the variable "namelist" to the function.
If namelist has block scope, the variable is also automatic, and hence
uninitialized, and hence contains garbage. If namelist has file
scope, the variable also has static duration and hence is
initialized to NULL.

In any case, getFileNames() cannot change the value stored in
the variable named "namelist" (unless it does not declare one
of its own, and does access the file-scope one). So it makes
no sense to pass the value in the first place, if namelist is
a block-scope variable.

If getFileNames() needs to modify namelist, it will need the
address of the variable:

extern int getFileNames(fi rst_type, struct dirent ***);
...
int main(void) {
struct dirent **namelist;
int n;

/* optional: namelist = NULL; */
n = getFileNames(H5 DIR, &namelist);

freeFileNames(n amelist, n); /* included from mylib.h */

Presumably the NULL-initialized file-scope static-duration version
causes freeFileNames() to be a no-op. Passing the uninitialized
value of the block-scope version presumably does not.

return 0;
}


You've hit the nail on the head. That's exactly what I've been having
trouble wrapping my mind around.

* Pass the address of the pointer in order to return it's value modified. *

The N indirection, dynamic allocation, and passing them has been
confusing me.
Thanks Chris
Jan 6 '06 #12
M.B

Dieter wrote:
Jack Klein wrote:
On Thu, 05 Jan 2006 22:44:27 -0500, Dieter <us**********@c omcast.net>
wrote in comp.lang.c:

Dieter wrote:

Hi.

In the snippet of code below, I'm trying to understand why when the

struct dirent ** namelist

is declared with "file" scope, I don't have a problem freeing the
allocated memory. But when the struct is declared in main (block scope)
it will segfault when passing namelist to freeFileNames() .

Since this seems to be just a matter of my understanding scope and
pointer parameter passing better, I only included what thought to be
relevant code. I'll happily provide compilable code if deemed necessary.

Please see commented lines:
struct dirent **namelist; /* file scope works */

int main(void)
{
/* struct dirent **namelist */ /* block scope doesn't work */
int n;

n = getFileNames(H5 DIR, namelist); /* included from mylib.h */
freeFileNames(n amelist, n); /* included from mylib.h */

return 0;
}
Thank you very much for your comments,
Dieter

Here's the actual code if needed. Although dirent.h is platform
specific, I think my question is relative to standard C.

The actual code is not needed, and is indeed off-topic. Your problem
has a great deal to do with how the function scandir(), which is
apparently from dirent.h, deals with pointers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>

#define H5DIR "/home/stella/data/h5/rawTables"

int getFileNames(ch ar *directory, struct dirent **namelist);
int freeFileNames(s truct dirent **namelist, int entries);

struct dirent **namelist;

When you define this pointer a file scope, it has static storage
duration and is therefore initialized to NULL. When you define it
inside a function, it has automatic storage duration by default and it
not initialized at all.

int main(void)
{
int n;

n = getFileNames(H5 DIR, namelist);
printf("%d\n",n );
err = freeFileNames(n amelist, n);
if (err==0)
printf("There wasn't any files");
return 0;
}

int getFileNames(ch ar *directory, struct dirent **namelist)
{
int n, i;

n = scandir(directo ry, &namelist, 0, alphasort);

[snip]

On the last line of code above, you pass a pointer to 'namelist'
(therefore a char ***) to scandir(). Presumably this function checks
whether the pointed-to char ** is NULL or not, and if it is NULL, it
allocates the necessary memory. And also presumably, if the
pointed-to char ** is not NULL, it assumes that it points to valid
memory and uses it. At the end you try to free a pointer that was not
allocated.

I would suggest that you study the documentation for the function
scandir() and see what the requirements are for that parameter.


Jack, I sincerely thank you for commenting.

NULL initialization was certainly an issue.

Dieter


I guess this is a scope issue for variable "namelist"
I suggest to change the function
int getFileName(cha r *,struct dirent ***);
and make necessary changes to code.
it may work fine

bcoz scandir i guess sets "struct dirent **" itself.
if its global all is fine, but local variables 0 its problem-same as
pass by value

thanks
-M.B

Jan 6 '06 #13
M.B
please chanmge function int getFileName(cha r *,struct dirent **);
to int getFileNames(ch ar *,struct dirent ***) and make necessary
changes to code to accomodate this

its a pass by value v/s pass by reference issue

Jan 6 '06 #14
M.B
This works without segfault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>

#define H5DIR "./"

int getFileNames(ch ar *directory, struct dirent ***namelist);
int freeFileNames(s truct dirent **namelist, int entries);
int main(void)
{
int n,err;
struct dirent **namelist;

n = getFileNames(H5 DIR,&namelist);
printf("%d\n",n );
err = freeFileNames(n amelist, n);
if (err==0)
printf("There wasn't any files");
return 0;

}

int getFileNames(ch ar *directory, struct dirent ***namelist)
{
int n, i;

n = scandir(directo ry, namelist, 0, alphasort);
if(n == -1){
perror("scandir returned: ");
exit(1);
}
if(n == 0){
printf("No files found. Quiting.\n\n");
exit(1);
}
for (i=0;i<n;i++){
printf("File: %s\n", (*namelist)[i]->d_name);
}

return n;

}

int freeFileNames(s truct dirent **namelist, int entries)
{
int i;

if (namelist == NULL)
return 0;
else{
printf("%d",ent ries);
for (i = 0; i < entries; i++){
free(namelist[i]);
namelist[i] = NULL;
printf("%d,", i);
}
puts("\n");
free(namelist);
namelist = NULL;
}

return 1;
}

Jan 6 '06 #15
M.B

Chuck F. wrote:
Dieter wrote:
Jack Klein wrote:
[snip]

On the last line of code above, you pass a pointer to
'namelist' (therefore a char ***) to scandir(). Presumably
this function checks whether the pointed-to char ** is NULL or
not, and if it is NULL, it allocates the necessary memory.
And also presumably, if the pointed-to char ** is not NULL, it
assumes that it points to valid memory and uses it. At the
end you try to free a pointer that was not allocated.

I would suggest that you study the documentation for the
function scandir() and see what the requirements are for that
parameter.
Jack, I sincerely thank you for commenting.

NULL initialization was certainly an issue.


All of which points out why we want queries to be topical. Once
you involve an unknown header (dirent) and an unknown function
(scandir) nobody can have any accurate idea what goes on. This is
why this whole thread should have been on a newsgroup dealing with
your system in the first place.

btw dirent or dirent.h is not alien. its of course not in ansi but in
posix (k&r also mentions it)
The fact that Jack could make an educated guess does not affect
this. His guess could well have been total nonsense, and could
have missed important factors. There is (in principle) noone here
to correct any mistakes.

I agree here. Anyone replying here want to help in any case. But we all
can help in giving suggestions but not spoonfeed. I may not know what
others know . knowlegde sharing is the idea here.
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>


Jan 6 '06 #16
M.B

Chuck F. wrote:
Dieter wrote:
Jack Klein wrote:
[snip]

On the last line of code above, you pass a pointer to
'namelist' (therefore a char ***) to scandir(). Presumably
this function checks whether the pointed-to char ** is NULL or
not, and if it is NULL, it allocates the necessary memory.
And also presumably, if the pointed-to char ** is not NULL, it
assumes that it points to valid memory and uses it. At the
end you try to free a pointer that was not allocated.

I would suggest that you study the documentation for the
function scandir() and see what the requirements are for that
parameter.
Jack, I sincerely thank you for commenting.

NULL initialization was certainly an issue.


All of which points out why we want queries to be topical. Once
you involve an unknown header (dirent) and an unknown function
(scandir) nobody can have any accurate idea what goes on. This is
why this whole thread should have been on a newsgroup dealing with
your system in the first place.

btw dirent or dirent.h is not alien. its of course not in ansi but in
posix (k&r also mentions it)
The fact that Jack could make an educated guess does not affect
this. His guess could well have been total nonsense, and could
have missed important factors. There is (in principle) noone here
to correct any mistakes.

I agree here. Anyone replying here want to help in any case. But we all
can help in giving suggestions but not spoonfeed. I may not know what
others know . knowlegde sharing is the idea here.
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>


Jan 6 '06 #17
M.B wrote:
This works without segfault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>

#define H5DIR "./"

int getFileNames(ch ar *directory, struct dirent ***namelist);
int freeFileNames(s truct dirent **namelist, int entries);
int main(void)
{
int n,err;
struct dirent **namelist;

n = getFileNames(H5 DIR,&namelist);
printf("%d\n",n );
err = freeFileNames(n amelist, n);
if (err==0)
printf("There wasn't any files");
return 0;

}

int getFileNames(ch ar *directory, struct dirent ***namelist)
{
int n, i;

n = scandir(directo ry, namelist, 0, alphasort);
if(n == -1){
perror("scandir returned: ");
exit(1);
}
if(n == 0){
printf("No files found. Quiting.\n\n");
exit(1);
}
for (i=0;i<n;i++){
printf("File: %s\n", (*namelist)[i]->d_name);
}

return n;

}

int freeFileNames(s truct dirent **namelist, int entries)
{
int i;

if (namelist == NULL)
return 0;
else{
printf("%d",ent ries);
for (i = 0; i < entries; i++){
free(namelist[i]);
namelist[i] = NULL;
printf("%d,", i);
}
puts("\n");
free(namelist);
namelist = NULL;
}

return 1;
}

MB, I can't express enough how much I appreciate your contribution.
Thank you for taking the time... and bending the sacred rules a little. :)
Jan 6 '06 #18
"Chuck F. " <cb********@yah oo.com> writes:
Dieter wrote:
Jack Klein wrote:
[snip]
On the last line of code above, you pass a pointer to
'namelist' (therefore a char ***) to scandir(). Presumably
this function checks whether the pointed-to char ** is NULL or
not, and if it is NULL, it allocates the necessary memory.
And also presumably, if the pointed-to char ** is not NULL, it
assumes that it points to valid memory and uses it. At the
end you try to free a pointer that was not allocated.
I would suggest that you study the documentation for the
function scandir() and see what the requirements are for that
parameter.

Jack, I sincerely thank you for commenting.
NULL initialization was certainly an issue.


All of which points out why we want queries to be topical. Once you
involve an unknown header (dirent) and an unknown function (scandir)
nobody can have any accurate idea what goes on. This is why this
whole thread should have been on a newsgroup dealing with your system
in the first place.

The fact that Jack could make an educated guess does not affect this.
His guess could well have been total nonsense, and could have missed
important factors. There is (in principle) noone here to correct any
mistakes.


In this case, there wasn't really any need to guess. The code causing
the problem was:

struct dirent **namelist;
int n;
n = getFileNames(H5 DIR, namelist);

It might as well have been:

struct foo **bar;
int n;
n = bleeble(blah, bar);

Regardless of what struct dirent/struct foo is, and regardless of what
getFileNames() or bleeble() does with its arguments, passing an
uninitialized variable to a function is almost certainly an error.
(Come to think of it, drop the "almost".)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 6 '06 #19
Dieter wrote:
int getFileNames(ch ar *directory, struct dirent **namelist)
{
int n, i;

n = scandir(directo ry, &namelist, 0, alphasort);


Hi,

As other groups members has remarked, the problem was in the call to
scandir (the program doesn't works if the variable is global and also
doesn't works if it is local. The only diference is how bad are the
effects).

I want only to remark two things about modify a function parameter:
a) The changes done to the value of a parameter will be always lost at
function return.
b) Change a parameter is under stylistic discussion (in particular, I
never do it. If necessary, I declare a local and init it with the
parameter value), and, who knows if allowed by standard. By example, a
SPARC CPU uses registers to pass parameters, so, the address of a
parameter is something that breaks to normal function prologs
(assembler code at start of fucntion).

In conclusion, any line of the kind "&parameter " must be carefully
reviewed.

Kind regards.

Jan 6 '06 #20

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

Similar topics

699
34262
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
18
3462
by: Minti | last post by:
I was reading some text and I came across the following snippet switch('5') { int x = 123; case '5': printf("The value of x %d\n", x); break; }
6
2482
by: Code Raptor | last post by:
Folks, I am hitting a segfault while free()ing allocated memory - to make it short, I have a linked list, which I try to free node-by-node. While free()ing the 28th node (of total 40), I hit a segfault. This is legacy code. I tried debugging this problem, and am not able to come up with a valid reason for this. Following function is being used to free: void DBFreePUF (DBPUFRec *userp) {
12
2730
by: G Patel | last post by:
I've seen some code with extern modifiers in front of variables declared inside blocks. Are these purely definitions (no definition) or are they definitions with static duration but external linkage? Not much on this in the FAQ or tutorials.
7
7718
by: seamoon | last post by:
Hi, I'm doing a simple compiler with C as a target language. My language uses the possibility to declare variables anywhere in a block with scope to the end of the block. As I remembered it this would be easily translated to C, but it seems variable declaration is only possible in the beginning of a block in C. Any suggestions how to get around this?
7
1477
by: BT | last post by:
Ok, for a school assignment we have to use a pointer for an array of ints, intstead of the usual X way, it compiles fine but when i run it I am getting a seg fault that i can't figure out how to fix. It occurs at this line: *d = rand() % 99 + 1 Here is the code for the first part of the program, the line that causes the seg fault is
8
3209
by: nobrow | last post by:
Okay ... Im out of practice. Is it not possible to have a 2D array where each column is of a different type, say an int and a struct*? The following seg faults for me and I cant figure out what I need to change. Thanks. #include <malloc.h> #include <string.h>
24
2671
by: Neal Becker | last post by:
One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed?
10
1878
by: somebody | last post by:
There are two files below named search.c and search.h. In the for loop in search.c, the for loop never exits, even if mystruct.field1 has no match. Instead of exiting the for loop it keeps going until it segfaults. This seems to be related to the strcmp with the NULL value. There are 2 comments below that indicate the segfaults. I guess the question is, when there is no match, how to I detect that and return without a segfault?
0
9680
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10173
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6788
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.