473,705 Members | 6,532 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3427
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.hel sinki.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)cybers pace.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(&dat a)) /* 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.com base.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*******@free net.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********@yah oo.com) (cb********@wor ldnet.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(ch ar *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(ch ar *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(ch ar *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.hel sinki.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(ch ar *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*******@free net.de)
Nov 13 '05 #10

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

Similar topics

9
29700
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 function with this statement several times and seems that it has successfully allocated the memory. and then at some iteration, it just gets this segmentation fault. The gdb gives the following message:
231
23150
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 (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
116
778
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, both the code to register the malloc and to write information into the malloc is solid. Why then ismy program returning an additional 4 characters? register malloc 1:
7
2215
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 http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
8
2557
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 failed. If anyone could point one out, I would be much obliged. I'm using MSVC .NET, but the only .NET specific newsgroups I could find were vbasic newsgroups and you'll agree a C malloc question is less off-topic here than there, at least. I...
15
2583
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 malloc always returned null at this moment and the program exited (even though if I malloc'ed only 20 bytes or something)... Then I googled for this problem and found something about a memory pool??? Is that standard C? I didn't understand it,...
68
15689
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; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
40
2588
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 struct? */ Seems to me there is no guarantee it will. /Why Tea
25
2251
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. --- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct {
23
2719
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 struct pxl { double lon, lat;
0
8768
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
8690
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
9274
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
9139
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...
0
8979
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7895
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6606
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2083
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.