473,416 Members | 1,525 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,416 software developers and data experts.

Please help! char* problems!

I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now when my function
returns, the values stored in the char* are some garbage values (perhaps
because I didn't allocate any memory for them).. but even if I allocate
memory in the function, on the return of this function I see garbage..
here is my code:
typedef char* string;

int main(int argc, char* argv[]) {

parseFile(argv[1], strX, strY);
...
... // values of strX and strY are garbage

}

void parseFile(const string file, string source, string target){

//read in some stuff from the file

source = malloc((size_t)sizeof(char)*X_SIZE_READ_FROM_FILE) ;
target = malloc((size_t)sizeof(char)*Y_SIZE_READ_FROM_FILE) ;

strcpy(source, STRING_READ_FROM_FILE);
strcpy(target, STRING_READ_FROM_FILE);

// print source and target... they're correct

}
can someone tell me what to do?

Thanks
Sona

Nov 13 '05 #1
5 2497
Sona <so**********@nospam.net> wrote in
news:3f********@clarion.carno.net.au:
I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now when my function
returns, the values stored in the char* are some garbage values (perhaps
because I didn't allocate any memory for them).. but even if I allocate
memory in the function, on the return of this function I see garbage..
here is my code:
typedef char* string;
First, typedef abuse like this should be avoided. You need to be
comfortable with pointers if you are going to be a C programmer. Besides,
char * does not mean you have a C string since you can have a pointer to a
bunch of 8-bit values without a null char.

int main(int argc, char* argv[]) {

parseFile(argv[1], strX, strY);
..
.. // values of strX and strY are garbage

}

void parseFile(const string file, string source, string target){

//read in some stuff from the file

source = malloc((size_t)sizeof(char)*X_SIZE_READ_FROM_FILE) ;
target = malloc((size_t)sizeof(char)*Y_SIZE_READ_FROM_FILE) ;

strcpy(source, STRING_READ_FROM_FILE);
strcpy(target, STRING_READ_FROM_FILE);

// print source and target... they're correct

}


Try this:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define STRING_READ_FROM_FILE_X "Hello from X file"
#define STRING_READ_FROM_FILE_Y "Good-bye from Y file"
#define X_SIZE_READ_FROM_FILE sizeof (STRING_READ_FROM_FILE_X)
#define Y_SIZE_READ_FROM_FILE sizeof (STRING_READ_FROM_FILE_Y)

/* Function correctly takes pointer to pointer to char, not pointer to
char ** since we need to modify the pointer and then what it points to.
*/
int parseFile(const char *pFile, char **pSrc, char **pTgt)
{
int failures = !0;

/* Set up so we can free() unconditionally on error.
*/
*pSrc = NULL;
*pTgt = NULL;

/* read in some stuff from the file since sizeof (char) is
** gauaranteed to be one, we don't include it in the malloc call.
*/
*pSrc = malloc(X_SIZE_READ_FROM_FILE);
*pTgt = malloc(Y_SIZE_READ_FROM_FILE);

if (*pSrc && *pTgt)
{
strcpy(*pSrc, STRING_READ_FROM_FILE_X);
strcpy(*pTgt, STRING_READ_FROM_FILE_Y);
failures = 0;

/* print source and target... they're correct
*/
}
else
{
free(*pSrc);
free(*pTgt);
}

return failures;
}

/* main()
*/
int main(int argc, char *argv[])
{
char *pStrX;
char *pStrY;

/* Pass pointers to pointers since you wish to change what
** address they point to.
*/
if (!parseFile(argv[1], &pStrX, &pStrY))
{
/* values of strX and strY are garbage
*/

/* All done with pointers' memory blocks.
*/
free(pStrX);
free(pStrY);
}

return 0;
}

--
- Mark ->
--
Nov 13 '05 #2


Sona wrote:
I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now when my function
returns, the values stored in the char* are some garbage values (perhaps
because I didn't allocate any memory for them).. but even if I allocate
memory in the function, on the return of this function I see garbage..
here is my code:
typedef char* string;

int main(int argc, char* argv[]) {

parseFile(argv[1], strX, strY);
..
.. // values of strX and strY are garbage

}

void parseFile(const string file, string source, string target){

//read in some stuff from the file

source = malloc((size_t)sizeof(char)*X_SIZE_READ_FROM_FILE) ;
target = malloc((size_t)sizeof(char)*Y_SIZE_READ_FROM_FILE) ;

strcpy(source, STRING_READ_FROM_FILE);
strcpy(target, STRING_READ_FROM_FILE);

// print source and target... they're correct

}
can someone tell me what to do?


You have declared strX and strY in function main. Since they are
not initialized, they may point to what you call garbage.
When you call function parseFile a copy the value of strX is
assigned to variable source and a copy of strY is made to the variable
target. You then change the values of target and source when you
assign them the return of function malloc. Then strcpy. All is ok in the
function and it prints the strings fine. But the variables in main
are not changed, thus the variables source and target point to the
allocated space. strX and strY still have garbage values.

A solution is to redefine the function parseFile so it will accept
the address of strX and strY.
Something similiar to this:
string parseFile(const string file, string *source, string *target);
and the call in main will be:
parseFile("const string", &strX, &strY);

An Example:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE_READ_FROM_FILE 128

typedef char *string;

string parseFile(const string file, string *source, string *target)
{
if(strlen(file) > SIZE_READ_FROM_FILE-1) return NULL;
if((*source = malloc(SIZE_READ_FROM_FILE)) == NULL) return NULL;
if((*target = malloc(SIZE_READ_FROM_FILE)) == NULL)
{
free(*source);
return NULL;
}
strcpy(*source, file);
strcpy(*target, file);
return *source;
}

int main(void)
{
string strX, strY;

if(parseFile("This is a test",&strX,&strY))
{
printf("strX = \"%s\"\nstrY = \"%s\"\n",strX,strY);
free(strX);
free(strY);
}
else puts("Failure in parseFile function");
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.combase.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #3
"Mark A. Odell" wrote:

[snip]
/* Set up so we can free() unconditionally on error.
*/
*pSrc = NULL;
*pTgt = NULL; [snip] *pSrc = malloc(X_SIZE_READ_FROM_FILE);
*pTgt = malloc(Y_SIZE_READ_FROM_FILE);

if (*pSrc && *pTgt)
{ [snip] }
else
{
free(*pSrc);
free(*pTgt);
}


I don't see why it's necessary to initialize them to NULL. Doesn't
malloc return NULL on failure anyway? Is it just a good habit? I can
see it would be useful in cases where you might return before some
of the mallocs.

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk.pbz' | rot13
Nov 13 '05 #4
Tom Zych <tz******@pobox.com> wrote in news:3F***************@pobox.com:
"Mark A. Odell" wrote:

[snip]
/* Set up so we can free() unconditionally on error.
*/
*pSrc = NULL;
*pTgt = NULL;

[snip]
*pSrc = malloc(X_SIZE_READ_FROM_FILE);
*pTgt = malloc(Y_SIZE_READ_FROM_FILE);

if (*pSrc && *pTgt)
{

[snip]
}
else
{
free(*pSrc);
free(*pTgt);
}


I don't see why it's necessary to initialize them to NULL.


It's not, the way I did it. I intended to bail if the first malloc failed
but forgot. You are correct, of course.

--
- Mark ->
--
Nov 13 '05 #5
I think you're having the same problem that I had, please refer to post
(very recent) with subject: return address of new memory.
It would be better if you posted your code, I'm doing something similar in
my programs, so first I give you that stuff and later I will simply paste
other people's stuff here:
main():
char *grayhistmatchfile = NULL;
char *ihsfile = NULL;
char *ihistmatchfile = NULL;
char *pcfile = NULL;
char *pcmtxfile = NULL;
char *inversepcfile = NULL;
char *graydwtfile = NULL;

ewrm_generateFileNames(&grayhistmatchfile, &ihsfile, &pcfile, &pcmtxfile,
&ihistmatchfile,
&graydwt1file, &graydwt2file, &graydwt3file, &resampledifile,
&copya1file, &copya2file, &copya3file,
&mergedihvdfile, &idwt1file, &idwt2file, &idwt3file,
&mergedidwt1file, &mergedidwt2file, &mergedihmfile, &hsresampledfile,
&rgbfile, &pc_xresampledfile, &inversepcfile, &stackoutput,
&lclerr);

void ewrm_generateFileNames(char **grayhistmatchfile, char **ihsfile, char
**pcfile, char **pcmtxfile, char **ihistmatchfile,
char **graydwt1file, char **graydwt2file, char **graydwt3file, char
**resampledifile,
char **copya1file, char **copya2file, char **copya3file,
char **mergedihvdfile, char **idwt1file, char **idwt2file, char
**idwt3file,
char **mergedidwt1file, char **mergedidwt2file, char **mergedihmfile, char
**hsresampledfile,
char **rgbfile, char **pc_xresampledfile, char **inversepcfile, char
**stackoutput,
Eerr_ErrorReport **inerr)
{

You copy to char * in this function, e.g.
*graydwt1file = strcpy(...);

}

************************************************** ***
You are getting confused with levels of indirection. A good rule of
thumb: if you find yourself assigning something to a function parameter
(not to what the parameter points at), then you're on the wrong track.
void getWaveletCoeffs(float *ld, float *hd, int *filterLen)
Change this to:
void getWaveletCoeffs(float **ld, float **hd, int *filterLen)

Why? Because you wish to assign to *pointers* in main(). Therefore
this function needs to receive *pointers to pointers*.
If you wish to assign to "foo type", then your function must receive
"pointers to foo type". This goes for any meaning of "foo type".
{
ld = (float*)malloc(2*SZFLOAT);
hd = (float*)malloc(2*SZFLOAT);
Change these to:
*ld = malloc(2*SZFLOAT);
*hd = malloc(2*SZFLOAT);

Note that while your old code assigns to ld and hd themselves, mine
assigns to what they point at. (See the * operator?) This is what I
was talking about earlier.
*ld++ = 0.7071;
*ld-- = 0.7071; *hd++ = -0.7071;
*hd-- = 0.7071;
These also need to be changed, to something like:
**ld = 0.7071;
*(*ld+1) = 0.7071;
**hd = -0.7071;
*(*hd+1) = 0.7071;
If I understood your logic correctly.

--
Pushkar Pradhan
"Peter "Shaggy" Haywood" <ph******@alphalink.com.au.STOP.SPAM> wrote in
message news:3f**************@news.alphalink.com.au... Groovy hepcat Sona was jivin' on Thu, 11 Sep 2003 22:49:08 +1000 in
comp.lang.c.
Please help! char* problems!'s a cool scene! Dig it!
I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now when my function
returns, the values stored in the char* are some garbage values (perhaps
because I didn't allocate any memory for them).. but even if I allocate
memory in the function, on the return of this function I see garbage..
This is a FAQ. Please go to
http://www.eskimo.com/~scs/C-faq/top.html and read it. Your question
(or part of it) is FAQ 4.8.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry &

W. Walker. I know it's not "technically correct" English; but since when was rock &

roll "technically correct"?
Nov 13 '05 #6

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

Similar topics

5
by: duikboot | last post by:
Hi all, I'm trying to export a view tables from a Oracle database to a Mysql database. I create insert statements (they look alright), but it all goes wrong when I try to execute them in Mysql,...
2
by: m3ckon | last post by:
Hi there, had to rush some sql and am now going back to it due to a slow db performance. I have a db for sales leads and have created 3 views based on the data I need to produce. However one...
0
by: Kurt Watson | last post by:
I’m having a different kind of problem with Hotmail when I sign in it says, "Web Browser Software Limitations Your Current Software Will Limit Your Ability to Use Hotmail You are using a web...
7
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title>...
23
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
13
by: sd00 | last post by:
Hi all, can someone give me some coding help with a problem that *should* be really simple, yet I'm struggling with. I need the difference between 2 times (Target / Actual) However, these times...
1
PEB
by: PEB | last post by:
POSTING GUIDELINES Please follow these guidelines when posting questions Post your question in a relevant forum Do NOT PM questions to individual experts - This is not fair on them and...
0
by: 2Barter.net | last post by:
newsmail@reuters.uk.ed10.net Fwd: Money for New Orleans, AL & GA Inbox Reply Reply to all Forward Print Add 2Barter.net to Contacts list Delete this message Report phishing Show original
6
by: jenipriya | last post by:
Hi all... its very urgent.. please........i m a beginner in oracle.... Anyone please help me wit dese codes i hv tried... and correct the errors... The table structures i hav Employee (EmpID,...
5
by: tabani | last post by:
I wrote the program and its not giving me correct answer can any one help me with that please and specify my mistake please it will be highly appreciable... The error arrives from option 'a' it asks...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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,...
0
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,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.