473,722 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_FRO M_FILE);
strcpy(target, STRING_READ_FRO M_FILE);

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

}
can someone tell me what to do?

Thanks
Sona

Nov 13 '05 #1
5 2536
Sona <so**********@n ospam.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_FRO M_FILE);
strcpy(target, STRING_READ_FRO M_FILE);

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

}


Try this:

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

#define STRING_READ_FRO M_FILE_X "Hello from X file"
#define STRING_READ_FRO M_FILE_Y "Good-bye from Y file"
#define X_SIZE_READ_FRO M_FILE sizeof (STRING_READ_FR OM_FILE_X)
#define Y_SIZE_READ_FRO M_FILE sizeof (STRING_READ_FR OM_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_R EAD_FROM_FILE);
*pTgt = malloc(Y_SIZE_R EAD_FROM_FILE);

if (*pSrc && *pTgt)
{
strcpy(*pSrc, STRING_READ_FRO M_FILE_X);
strcpy(*pTgt, STRING_READ_FRO M_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(arg v[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_FRO M_FILE);
strcpy(target, STRING_READ_FRO M_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("cons t 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_REA D_FROM_FILE)) == NULL) return NULL;
if((*target = malloc(SIZE_REA D_FROM_FILE)) == NULL)
{
free(*source);
return NULL;
}
strcpy(*source, file);
strcpy(*target, file);
return *source;
}

int main(void)
{
string strX, strY;

if(parseFile("T his is a test",&strX,&st rY))
{
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.com base.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_R EAD_FROM_FILE);
*pTgt = malloc(Y_SIZE_R EAD_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.c om:
"Mark A. Odell" wrote:

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

[snip]
*pSrc = malloc(X_SIZE_R EAD_FROM_FILE);
*pTgt = malloc(Y_SIZE_R EAD_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 *grayhistmatchf ile = NULL;
char *ihsfile = NULL;
char *ihistmatchfile = NULL;
char *pcfile = NULL;
char *pcmtxfile = NULL;
char *inversepcfile = NULL;
char *graydwtfile = NULL;

ewrm_generateFi leNames(&grayhi stmatchfile, &ihsfile, &pcfile, &pcmtxfile,
&ihistmatchfile ,
&graydwt1fil e, &graydwt2fil e, &graydwt3fil e, &resampledifile ,
&copya1file, &copya2file, &copya3file,
&mergedihvdfile , &idwt1file, &idwt2file, &idwt3file,
&mergedidwt1fil e, &mergedidwt2fil e, &mergedihmfi le, &hsresampledfil e,
&rgbfile, &pc_xresampledf ile, &inversepcfi le, &stackoutput ,
&lclerr);

void ewrm_generateFi leNames(char **grayhistmatch file, char **ihsfile, char
**pcfile, char **pcmtxfile, char **ihistmatchfil e,
char **graydwt1file, char **graydwt2file, char **graydwt3file, char
**resampledifil e,
char **copya1file, char **copya2file, char **copya3file,
char **mergedihvdfil e, char **idwt1file, char **idwt2file, char
**idwt3file,
char **mergedidwt1fi le, char **mergedidwt2fi le, char **mergedihmfile , char
**hsresampledfi le,
char **rgbfile, char **pc_xresampled file, char **inversepcfile , char
**stackoutput,
Eerr_ErrorRepor t **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 getWaveletCoeff s(float *ld, float *hd, int *filterLen)
Change this to:
void getWaveletCoeff s(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*SZFLOA T);
*hd = malloc(2*SZFLOA T);

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******@alpha link.com.au.STO P.SPAM> wrote in
message news:3f******** ******@news.alp halink.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 "technicall y correct" English; but since when was rock &

roll "technicall y correct"?
Nov 13 '05 #6

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

Similar topics

5
3490
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, because the dates must have quotes on each side. I just don't know how make the dates right. Well I'll just show you the code and some insert statements it generates. Could anyone please help me?
2
1927
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 o the views, which has subqueries to the other views is VERY slow and it needs to be speeded up, but am unsure how, can anyone help... below is the sql?
0
1702
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 browser that Hotmail does not support. If you continue to use your current browser software we cannot guarantee that Hotmail will work correctly for you". Please help, this is very annoying. I have been searching for help on
7
3614
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> </head> <style type="text/css">
23
3280
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 to create certain textboxes, labels, and combo boxes? Any ideas would be appreciated. Thanks
13
2147
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 will fall somewhere between a Start & End time Further more, there will be Break & Lunch times between Start & End. Example... Start 08:00 Break start 10:30
1
54520
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 we instruct our experts to ignore any such PMs completely Be sure to give the version of Access that you are working with and the Platform and OS if applicable.
0
3052
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
3323
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, EmpName,DeptID,DateOfJoin, Sal, Addr) Finance (EmpID, Sal) Club (Clubname, EmpID, Fee, DateOfJoin) Leave (EmpID, Date) Department (DeptID, DeptName, NoOfEmployees)...
5
2312
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 for user name, check in the system but does not return the correct answer please help me with it. or if you have better way of doing it would you please mind to tell me.. thanks.. #!/usr/bin/perl -w #use Getopt::Std;
0
8867
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
8740
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9239
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
9158
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
5996
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
4503
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
3208
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
2606
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2148
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.