473,388 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

return a string array

hi

i would like to return a string

Expand|Select|Wrap|Line Numbers
  1. char *readFile(char *tmp_dir_led, char *directory, char *filename)
  2. {
  3. FILE *fp;
  4. char line[LINE_MAX];
  5. snprintf(tmp_mnt_dir_led, sizeof(tmp_mnt_dir_led),"%s/%s",
  6. directory,filename);
  7. fp = fopen(tmp_mnt_dir_led, "r");
  8. if(fp!=NULL)
  9. {
  10. fgets(line, LINE_MAX, fp);
  11. }
  12.  
  13. return line;
  14. }
  15.  
in my block main i do:

printf("%s\n",readFiletmp_mnt_dir_led, mnt_dir_led,
"B_L1_HLD_GRN_NOR_Run_Counter.txt"));

i see some crap character

are there any way to do resolve this problem in C?

thanks

Nov 14 '05 #1
16 2608


collinm wrote:
hi

i would like to return a string
[... returns a pointer to an `auto' variable ...]


This is Question 7.5 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

--
Er*********@sun.com

Nov 14 '05 #2
In article <11*********************@o13g2000cwo.googlegroups. com>,
collinm <co*****@laboiteaprog.com> wrote:
i would like to return a string char *readFile(char *tmp_dir_led, char *directory, char *filename)
{
FILE *fp;
char line[LINE_MAX]; return line;
}


line is an variable of storage class "automatic". Usually that means
it will be allocated on the stack. You then return line, which will
silently decay from being an array to become a pointer to the first
element of the array. But when that pointer value is used outside
the routine, it points to something that logically no longer exists
(the automatic storage.)

If you want to return a generated character array, you will have to
malloc() [or equivilent] space for the array and return it. And
remember to free() the space afterwards.
--
Any sufficiently advanced bug is indistinguishable from a feature.
-- Rich Kulawiec
Nov 14 '05 #3
"collinm" <co*****@laboiteaprog.com> wrote:
char *readFile(char *tmp_dir_led, char *directory, char *filename)
{
FILE *fp;
char line[LINE_MAX];
snprintf(tmp_mnt_dir_led, sizeof(tmp_mnt_dir_led),"%s/%s", directory,filename);


Apart from the answer by Eric, you need to realise that this is also a
bug. sizeof on a pointer object gives you the size of the pointer
itself, not of the area it points at. Most likely this means that even
if you solve the problem with the return value, you will not be able to
open the file because the file name gets truncated; if you pass in a
pointer to an excessively short char area (or have excessively large
pointer types...), you may cause undefined behaviour by writing past the
end of the name buffer.

Richard
Nov 14 '05 #4

Walter Roberson wrote:
In article <11*********************@o13g2000cwo.googlegroups. com>,
collinm <co*****@laboiteaprog.com> wrote:
i would like to return a string

char *readFile(char *tmp_dir_led, char *directory, char *filename)
{
FILE *fp;
char line[LINE_MAX];

return line;
}


line is an variable of storage class "automatic". Usually that means
it will be allocated on the stack. You then return line, which will
silently decay from being an array to become a pointer to the first
element of the array. But when that pointer value is used outside
the routine, it points to something that logically no longer exists
(the automatic storage.)

If you want to return a generated character array, you will have to
malloc() [or equivilent] space for the array and return it. And
remember to free() the space afterwards.
--
Any sufficiently advanced bug is indistinguishable from a feature.
-- Rich Kulawiec


ok i need to create a dynamic array in the function and free it outside
the function

Nov 14 '05 #5
i do:

char tmp_mnt_dir_led[75];

if(!(mnt_dir_led = getenv("LED_DISPLAY_DIR")))
{
printf("%s - Incapable de lire la variable: LED_DISPLAY_DIR\n",
strerror(errno));
return 1;
}

Nov 14 '05 #6
collinm wrote:
Walter Roberson wrote:
collinm <co*****@laboiteaprog.com> wrote:
i would like to return a string

char *readFile(char *tmp_dir_led, char *directory, char *filename)
{
FILE *fp;

.... snip ...
(the automatic storage.)

.... snip ...
ok i need to create a dynamic array in the function and free it
outside the function


Do I conclude that Roberson has finally corrected his quote char,
and can come off my PLONK list? The other possibility is that you
have corrected his quotes.

--
"If you want to post a followup via groups.google.com, 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
Nov 14 '05 #7
CBFalconer <cb********@yahoo.com> scribbled the following:
collinm wrote:
Walter Roberson wrote:
collinm <co*****@laboiteaprog.com> wrote:
i would like to return a string

char *readFile(char *tmp_dir_led, char *directory, char *filename)
{
FILE *fp;

... snip ...
> (the automatic storage.)

Do I conclude that Roberson has finally corrected his quote char,
and can come off my PLONK list? The other possibility is that you
have corrected his quotes.


You conclude correct. He has corrected the quote char.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"A computer program does what you tell it to do, not what you want it to do."
- Anon
Nov 14 '05 #8
On Fri, 25 Mar 2005 18:32:55 GMT, in comp.lang.c , CBFalconer
<cb********@yahoo.com> wrote:
Do I conclude that Roberson has finally corrected his quote char,
he seems to have changed it, yes. For which I want to thank him for
reconsidering the views expressed by several others.
and can come off my PLONK list?


Thats up to you !

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #9
Mark McIntyre wrote:
<cb********@yahoo.com> wrote:
Do I conclude that Roberson has finally corrected his quote char,


he seems to have changed it, yes. For which I want to thank him for
reconsidering the views expressed by several others.


I will also thank him. It seems others were more persuasive than
I.

--
"If you want to post a followup via groups.google.com, 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

Nov 14 '05 #10
"collinm" <co*****@laboiteaprog.com> writes:
i do:

char tmp_mnt_dir_led[75];

if(!(mnt_dir_led = getenv("LED_DISPLAY_DIR")))
{
printf("%s - Incapable de lire la variable: LED_DISPLAY_DIR\n",
strerror(errno));
return 1;
}


The standard doesn't say that getenv() sets errno on failure (and in
fact it typically doesn't).

The only reason getenv("LED_DISPLAY_DIR") should fail is if the
environment variable isn't set, so errno wouldn't give you any useful
information anyway.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #11
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
:The only reason getenv("LED_DISPLAY_DIR") should fail is if the
:environment variable isn't set, so errno wouldn't give you any useful
:information anyway.

My standard is at work, so I can't check to confirm, but is
it certain that getenv() will return a pointer to an
already already-existing environment variable object? Or is it
permitted to return a copy?

The documentation I'm looking at at the moment implies that it
uses the actual pointers and that the space pointed to is modifiable
(not read-only... but you'd still have to be careful not to extend it).
I'm not sure whether that's implementation behaviour or standard-
defined behaviour though.
--
'The short version of what Walter said is "You have asked a question
which has no useful answer, please reconsider the nature of the
problem you wish to solve".' -- Tony Mantler
Nov 14 '05 #12
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
The only reason getenv("LED_DISPLAY_DIR") should fail is if the
environment variable isn't set, so errno wouldn't give you any useful
information anyway.


My standard is at work, so I can't check to confirm, but is
it certain that getenv() will return a pointer to an
already already-existing environment variable object? Or is it
permitted to return a copy?

The documentation I'm looking at at the moment implies that it
uses the actual pointers and that the space pointed to is modifiable
(not read-only... but you'd still have to be careful not to extend it).
I'm not sure whether that's implementation behaviour or standard-
defined behaviour though.


[I've taken the liberty of changing the unconventional ":" quoting
prefix to "> " above.]

C99 7.20.4.5 says:

The getenv function returns a pointer to a string associated with the
matched list member. The string pointed to shall not be modified by
the program, but may be overwritten by a subsequent call to the getenv
function. If the specified name cannot be found, a null pointer is
returned.

Since the "shall" is not in a constraint, attemptying to modify the
string would invoke undefined behavior. So an implementation is free
to return a pointer to an existing string to a unique copy, or to a
statically allocated copy.

(On one system I just tested, modifying the string affects the
environment, but of course that's a valid consequence of undefined
behavior.)

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #13
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
C99 7.20.4.5 says: The getenv function returns a pointer to a string associated with the
matched list member. The string pointed to shall not be modified by
the program, but may be overwritten by a subsequent call to the getenv
function. If the specified name cannot be found, a null pointer is
returned. Since the "shall" is not in a constraint, attemptying to modify the
string would invoke undefined behavior.


Ah, the IRIX 6.2 putenv() is -defined- such that if one modifies
the string after putenv()'ing it, then the value *is* changed.
I see though that by IRIX 6.5 the putenv() does not say anything like that.

The IRIX 6.5 putenv() talks about potential failure if the environment
cannot be expanded by malloc(), but the IRIX 6.5 getenv() does not
mention the possibility of a malloc() failure; if the two are
self-consistant the implication would be that at least for IRIX 6.5,
getenv() returns a direct pointer, not a copy of a string.

Is there anything similar that can be deduced in the C standard?
Are routines allowed failure modes such as malloc() errors
that are not listed in the standard?
This next point starts to stray a bit off-standard, but I seem
to recall seeing getenv() listed in POSIX's interrupt-safe
routines, and I don't -recall- seeing any getenv_r() or
similar name defined as a thread-safe version of getenv().
If those recollections are correct, then the implication would
be that in POSIX compliant implementations, getenv() would
be effectively constrained from malloc()'ing to produce a copy
of the string.
[These questions are apropos of your comment about failure modes
of getenv(), with me aiming towards the question "Is
out-of-memory a potential further failure mode of getenv() ?"]
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Nov 14 '05 #14
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
C99 7.20.4.5 says:
The getenv function returns a pointer to a string associated with the
matched list member. The string pointed to shall not be modified by
the program, but may be overwritten by a subsequent call to the getenv
function. If the specified name cannot be found, a null pointer is
returned.

Since the "shall" is not in a constraint, attemptying to modify the
string would invoke undefined behavior.


Ah, the IRIX 6.2 putenv() is -defined- such that if one modifies
the string after putenv()'ing it, then the value *is* changed.
I see though that by IRIX 6.5 the putenv() does not say anything like that.


putenv() is not a standard C function. The only interface to
environment variables defined by the standard is the getenv()
function; there's no way to set an environment variable, or even to
determine which variables are set.

[...] Is there anything similar that can be deduced in the C standard?
Are routines allowed failure modes such as malloc() errors
that are not listed in the standard?


I'm not sure. The standard's definition of getenv() seems to be
designed to allow an implementation to return an existing string
rather than allocating a copy -- and if it returned a pointer to a
malloc()ed string, the caller would have no way of knowing it needs to
be free()d, creating a memory leak.

Of course, any function can fail by running out of memory (invoking
undefined behavior).

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #15
Walter Roberson wrote:
Keith Thompson <ks***@mib.org> wrote:
The only reason getenv("LED_DISPLAY_DIR") should fail is if the
environment variable isn't set, so errno wouldn't give you any
useful information anyway.
My standard is at work, so I can't check to confirm, but is
it certain that getenv() will return a pointer to an already
already-existing environment variable object? Or is it
permitted to return a copy?

The documentation I'm looking at at the moment implies that it
uses the actual pointers and that the space pointed to is
modifiable (not read-only... but you'd still have to be careful
not to extend it). I'm not sure whether that's implementation
behaviour or standard- defined behaviour though.


(Obnoxious non-standard quote marks corrected)
From N869:


7.20.4.4 The getenv function

Synopsis
[#1]
#include <stdlib.h>
char *getenv(const char *name);

Description

[#2] The getenv function searches an environment list,
provided by the host environment, for a string that matches
the string pointed to by name. The set of environment names
and the method for altering the environment list are
implementation-defined.

[#3] The implementation shall behave as if no library
function calls the getenv function.

Returns

[#4] The getenv function returns a pointer to a string
associated with the matched list member. The string pointed
to shall not be modified by the program, but may be
overwritten by a subsequent call to the getenv function. If
the specified name cannot be found, a null pointer is
returned.

--
"If you want to post a followup via groups.google.com, 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

Nov 14 '05 #16

collinm wrote:
hi

i would like to return a string

Expand|Select|Wrap|Line Numbers
  1.  char *readFile(char *tmp_dir_led, char *directory, char *filename)
  2.  {
  3.      FILE *fp;
  4.      char line[LINE_MAX];
  5.      snprintf(tmp_mnt_dir_led, sizeof(tmp_mnt_dir_led),"%s/%s",
  6.  directory,filename);
  7.      fp = fopen(tmp_mnt_dir_led, "r");
  8.      if(fp!=NULL)
  9.      {
  10.          fgets(line, LINE_MAX, fp);
  11.      }
  12.      return line;
  13.  }
  14.  

in my block main i do:

printf("%s\n",readFiletmp_mnt_dir_led, mnt_dir_led,
"B_L1_HLD_GRN_NOR_Run_Counter.txt"));

i see some crap character

are there any way to do resolve this problem in C?

thanks


Nov 14 '05 #17

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

Similar topics

9
by: Steve | last post by:
Hello (and a happy new year) I'm quite new to C++ and have to programm something for school and can't get my head around a couple of things, but at the moment this one is the most important for...
0
by: Marc van Boven | last post by:
I'm stuck with the following problem: My nusoap-client calls a server-function giveCombination(). The function giveCombination should return something like array( => array( 'a_id' => 6,...
23
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
4
by: Woody Splawn | last post by:
How would I pass an array back to a sub routine from a function? That is, I have a function that looks like this Public Function arrayTest() As Array Dim states() As String = { _ "AZ", "CA",...
7
by: nafri | last post by:
hello all, I want to create a function that returns the first element of the Array that is input to it. However, the Input Array can be an Array of points, double, or anyother type, which means...
6
by: Andrew | last post by:
Hi all, I have a method that wants to return an array. What datatype should I use ? I tried using an "Array" but there was a compilation error. Why ? public Array setReviewAll2 (int intNumQn)...
12
by: Aff | last post by:
Brothers , i am facing a problem which is as follow: class poly { private: char name; int capacity; public: poly(char , int );
18
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
10
by: Raj | last post by:
I need a VB function to return array of collections like Private Type Employee empname as string address as string salary as integer deptno as integer End Type dim employees() as Employee
14
by: =?Utf-8?B?QmVu?= | last post by:
Hi all, I'm trying to understand the concept of returning functions from the enclosing functions. This idea is new to me and I don't understand when and why I would need to use it. Can someone...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
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...

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.