473,404 Members | 2,137 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,404 software developers and data experts.

malloc problem

Hi,

Here is my source code :

void getData(char *theData)
{
theData = malloc(500);
strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
}

void main()
{
char *data;
getData(&data);
printf("\n%s\n",data); // = NULL ???
}
malloc is ok, into the function I get what I want, but data is equal
to NULL in main().

What is the problem ?

thanks for your help.

thierry
Nov 13 '05 #1
9 3407
Thierry <th*****@sockho.com> scribbled the following:
Hi, Here is my source code : void getData(char *theData)
{
theData = malloc(500);
strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
} void main()
{
char *data;
getData(&data);
printf("\n%s\n",data); // = NULL ???
}
malloc is ok, into the function I get what I want, but data is equal
to NULL in main(). What is the problem ?


It is not enough to supply the address of data in main(). The getData()
function must use it correctly. Like so:
void getData(char **theData) {
*theData = malloc(500);
if (*theData) {
strcpy(*theData, "Hello world");
printf("%s\n", *theData);
}
}

I think a message somewhat like "Assigning new values to function
parameters is a sign of a design problem" every 5 minutes to
comp.lang.c might help a little to cure this very common newbies'
problem.

PS. You also should replace void main() by int main().

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"I am looking for myself. Have you seen me somewhere?"
- Anon
Nov 13 '05 #2


On 10/15/2003 10:49 AM, Thierry wrote:
Hi,

Here is my source code :

void getData(char *theData)
{
theData = malloc(500);
strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
}

void main()
{
char *data;
getData(&data);
printf("\n%s\n",data); // = NULL ???
}
malloc is ok, into the function I get what I want, but data is equal
to NULL in main().

What is the problem ?
I suspect your compiler is already telling you with a warning. Your parameter
for getData should be of type char **, not char *, and dereferenced accordingly.

Ed.
thanks for your help.

thierry


Nov 13 '05 #3
Thierry <th*****@sockho.com> spoke thus:
void getData(char *theData)
{
theData = malloc(500);
strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
} void main()
{
char *data;
getData(&data);
printf("\n%s\n",data); // = NULL ???
}


What is &data? It's a pointer to a char*, right? So &data is a char**, which
is not what getData takes as a parameter.

void getData(char **theData) {
*theData=malloc(500);
if( !*theData ) return; /* check for NULL */
strcpy( *theData, "Hello, world!" );
printf( "\n%s\n", *theData );
}

Also, main() *always* returns an int. void main() is wrong.

--
Christopher Benson-Manica | Upon the wheel thy fate doth turn,
ataru(at)cyberspace.org | upon the rack thy lesson learn.
Nov 13 '05 #4


Thierry wrote:
Hi,

Here is my source code :

void getData(char *theData) char *getData(char **theData) {
theData = malloc(500); *theData = malloc(500);
/* make sure the allocations were successful */
if(*theData != NULL)
{ strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
} return *theData;
}
void main() int main(void) {
char *data; /* assign it NULL for safety */
char *data = NULL; getData(&data); if(getData(&data)) /* if success then print */ printf("\n%s\n",data); // = NULL ???
free(data);
return 0; }
malloc is ok, into the function I get what I want, but data is equal
to NULL in main().

What is the problem ?


The primary error is the incorrect parameter in function getData.
It should be char **theData, not char *theData.
--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.combase.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #5
th*****@sockho.com (Thierry) wrote:
Hi,

Here is my source code :
<code snipped>
malloc is ok, into the function I get what I want, but data is equal
to NULL in main().

What is the problem ?


Joona has already answered your question.
However, here is another approach:

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

#define DATA_SIZE 500

char *getData( void )
{
char *theData = malloc( DATA_SIZE );
if ( theData == NULL ) /* [1] */
exit( EXIT_FAILURE );
strcpy( theData, "hello world..." );
return theData;
}

int main( void ) /* [2] */
{
char *data;

data = getData();
printf("\n%s\n",data);

return EXIT_SUCCESS; /* [2] */
}

[1] *Always* check the return value of malloc().
[2] main() *always* returns an int (on hosted implementations).

HTH

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #6
Joona I Palaste wrote:
.... snip ...
It is not enough to supply the address of data in main(). The
getData() function must use it correctly. Like so:

void getData(char **theData) {
*theData = malloc(500);
if (*theData) {
strcpy(*theData, "Hello world");
printf("%s\n", *theData);
}
}

I think a message somewhat like "Assigning new values to
function parameters is a sign of a design problem" every 5
minutes to comp.lang.c might help a little to cure this very
common newbies' problem.


On the contrary, parameters are pre-initialized local variable,
and should be so used. What needs to be dunned into newbies is
that they don't return values. Therefore a better form of the OPs
routine would be:

char *getData(void) {
char *theData

theData = malloc(500);
if (theData) {
strcpy(theData, "Hello world");
printf("%s\n", theData);
}
return theData;
}

and the call in main should be:

theData = getdata()

with no taking of addresses nor confusion. The "theData" visible
within getData() is purely local, and has no connection with the
"theData" visible in main.

Functions primarily return values. Let them do so.

--
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 13 '05 #7
> I think a message somewhat like "Assigning new values to function
parameters is a sign of a design problem" every 5 minutes to
comp.lang.c might help a little to cure this very common newbies'
problem.

PS. You also should replace void main() by int main().


Is it not recommended to assign new value to function parameter ?

How can I do If I have 2 variables to change at one time (in a function)

For example void changeValues(char *value1, char *value2);

I think it's the right solution to do this without using global variables.

What do you think ?

Thanks for you help.

thierry
Nov 13 '05 #8
Thierry <th*****@sockho.com> scribbled the following:
I think a message somewhat like "Assigning new values to function
parameters is a sign of a design problem" every 5 minutes to
comp.lang.c might help a little to cure this very common newbies'
problem.

PS. You also should replace void main() by int main().
Is it not recommended to assign new value to function parameter ? How can I do If I have 2 variables to change at one time (in a function) For example void changeValues(char *value1, char *value2); I think it's the right solution to do this without using global variables. What do you think ?


Did you have in mind this kind of solution?
void changeValues(char *value1, char *value2)
{
char tmp;
tmp = *value1;
*value1 = *value2;
*value2 = tmp;
}
If so, then please note that the above does NOT assign new values to
function parameters. It assigns new values to what the parameters
POINT TO. This is very much OK design.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The truth is out there, man! Way out there!"
- Professor Ashfield
Nov 13 '05 #9
th*****@sockho.com (Thierry) wrote:
I think a message somewhat like "Assigning new values to function
parameters is a sign of a design problem" every 5 minutes to
comp.lang.c might help a little to cure this very common newbies'
problem.


Is it not recommended to assign new value to function parameter ?
How can I do If I have 2 variables to change at one time (in a function)

For example void changeValues(char *value1, char *value2);

I think it's the right solution to do this without using global variables.
What do you think ?


Alternatively, you may pass|return a structure to|from the function.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #10

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

Similar topics

9
by: Bin Lu | last post by:
I keep getting this malloc problem when my program tries to allocate memory for some pointer. The statement is like: rsv_cache = (rsvcache *) malloc (sizeof(rsvcache)); It goes through the...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
116
by: Kevin Torr | last post by:
http://www.yep-mm.com/res/soCrypt.c I have 2 malloc's in my program, and when I write the contents of them to the screen or to a file, there aren addition 4 characters. As far as I can tell,...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
8
by: Snis Pilbor | last post by:
First, let me announce that this is very possibly off-topic because malloc is a specific third party accessory to c, etc. I spent about an hour trying to find a more appropriate newsgroup and...
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
40
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd...
25
by: Why Tea | last post by:
Thanks to those who have answered my original question. I thought I understood the answer and set out to write some code to prove my understanding. The code was written without any error checking....
23
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...
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...

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.