473,756 Members | 4,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple malloc() problem

Can someone explain to a C newbie why this doesn't work as I expect it
to work? (expectations clearly outlined in the printf statement in
main routine)

OS: Linux 2.4.26
GCC: 2.95.4

void modify_pointer( char *);

int main(int argc, char *argv[]) {
char *ptr_to_string;
modify_pointer( ptr_to_string);
printf("but why doesn't this say hello? %s\n", ptr_to_string);
}

void modify_pointer( char *the_ptr) {
the_ptr = (char *) malloc(strlen(" hello"));
strcpy(the_ptr, "hello");
printf("this says hello: %s\n", the_ptr);
}

--
output:

this says hello: hello
but why doesn't this say hello? p�

---
Nov 14 '05 #1
33 2282

"hermit_cra b67" <he***********@ yahoo.com> wrote in message news:52******** *************** ***@posting.goo gle.com...
Can someone explain to a C newbie why this doesn't work as I expect it
to work? (expectations clearly outlined in the printf statement in
main routine)

The problem isn't with the malloc (except the memory leakage here).
ptr_to_string has been passed by value, so the assigment

the_ptr = (char *) malloc(strlen(" hello")); /* don't cast */

is local to the modify_pointer( ). Do as follows:

OS: Linux 2.4.26
GCC: 2.95.4

void modify_pointer( char *);
void modify_pointer( char **);
int main(int argc, char *argv[]) {
char *ptr_to_string;
modify_pointer( ptr_to_string);
modify_pointer( &ptr_to_string) ;
printf("but why doesn't this say hello? %s\n", ptr_to_string);
}

void modify_pointer( char *the_ptr) {
the_ptr = (char *) malloc(strlen(" hello"));
strcpy(the_ptr, "hello");
printf("this says hello: %s\n", the_ptr);
}


void modify_pointer( char **the_ptr) {
*the_ptr = malloc(sizeof(" hello"));
strcpy(*the_ptr , "hello");
printf("this says hello: %s\n", *the_ptr);
}

This might be of some help:

In C, the only true method of parameter passing is known as "call by value".
The following example demonstrates the last statement:

#include <stdlib.h>

void
raisin ( float x ) { /* process x here */ }

void
grape ( float *xp ) { /* process xp here */ }

int
main ( void )
{
float f;
float *fp = &f;

/* ... */
raisin ( f );
grape ( fp );
return EXIT_SUCCESS;
}

When the declaration of an argument (f and fp) matches with the declaration
of the corresponding parameter (x and xp), then the argument has been passed by
value. And, when an argument is passed by value, any modification the called-
function makes to the parameter does not reflect in the calling-function. So,
any modification to xp does not reflect in fp, however, any modification to *xp
reflects in f.

--
Vijay Kumar R Zanvar
Pointers and Arrays - http://www.geocities.com/vijoeyz/art...dex.html#seq21
Nov 14 '05 #2
In 'comp.lang.c', he***********@y ahoo.com (hermit_crab67) wrote:
Can someone explain to a C newbie why this doesn't work as I expect it
to work? (expectations clearly outlined in the printf statement in
main routine)

OS: Linux 2.4.26
GCC: 2.95.4

void modify_pointer( char *);
Starts badly. If you want to modify an object, you must pass the address of
it. Remember, in C, only the values are passed.

void modify_pointer( char **pp);

Your problem is covered by the FAQ:

http://www.eskimo.com/~scs/C-faq/q4.8.html
int main(int argc, char *argv[]) {
char *ptr_to_string;
This pointer is uninitialized.
modify_pointer( ptr_to_string);
Passing an uninitialized value to a function invokes an undefined behaviour.
Anything can happen. A decent and well-configured compiler should have warned
you about that.

Because you are using gcc (note: gcc is not GCC), I suggest you add this to
your command line:

-W -Wall -O2

and the following in addition if you want to comply to the C standard:

-ansi -pedantic
printf("but why doesn't this say hello? %s\n", ptr_to_string);
Be sure that <stdio.h> is included. printf() needs a prototype. It's
mandatory.
}

void modify_pointer( char *the_ptr) {
the_ptr = (char *) malloc(strlen(" hello"));
Modifiying the value of a parameter is often the indication of a bad design.

No need for the cast. Be sure that you have included <stdlib.h>. malloc() can
fail. You must test the returned value against NULL.

strlen() wants <string.h>. It returns the length of the string, not it's
size. You're off by one.

char * the_ptr = malloc(strlen(" hello") + 1);

or, in this special case involving a string literal:

char * the_ptr = malloc(sizeof "hello");
strcpy(the_ptr, "hello");
But it is recommended to avoid such repetitions.
- Not all compilers are smart enough to merge similar string literals, hence
a waste of space.
- It makes maintenance a hell

I recommend an initialized array of const char:

char const s[] = "hello";
char * the_ptr = malloc(strlen(S ) + 1);

if (the_ptr != NULL)
{
strcpy(the_ptr, S);
<...>
}
printf("this says hello: %s\n", the_ptr);
}


Not to mention that the value of 'the_ptr' must now be returned via the new
char ** pp parameter (after having checked that pp is not NULL, of course).

if (pp != NULL)
{
*pp = the_ptr;
}

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #3
Emmanuel Delahaye wrote:
Modifiying the value of a parameter is often the indication of a bad design.


I'm interested in your thoughts behind this statement.

Case

Nov 14 '05 #4
In 'comp.lang.c', Case <no@no.no> wrote:
Modifiying the value of a parameter is often the indication of a bad
design.


I'm interested in your thoughts behind this statement.


The code given by the original poster is a perfect illustration of this
statement.

Apart for micro-optimisation purpose, there is not good reasons for a
parameter to have its value changed. This is the reason why, at a first
glance, I recommend to define the parameters with const. If it clashes
somewhere, it means that it's time to think harder about the design.

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #5
Case wrote:
Emmanuel Delahaye wrote:
Modifiying the value of a parameter is often the indication of
a bad design.


I'm interested in your thoughts behind this statement.


This is a religious issue, on which E.D. and I disagree. I treat
parameters as externally initialized local variables (which they
are). If a function is so long that I can't easily spot the need
for the original value, then there is a design problem and the
function needs to be broken up into smaller and simpler functions.

--
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 14 '05 #6
In <Xn************ **************@ 212.27.42.74> Emmanuel Delahaye <em**********@n oos.fr> writes:
In 'comp.lang.c', Case <no@no.no> wrote:
Modifiying the value of a parameter is often the indication of a bad
design.
I'm interested in your thoughts behind this statement.


Like most such statements made by Emmanuel, it's a matter of pure
religion taken as fact.
The code given by the original poster is a perfect illustration of this
statement.


And the following code is a perfect rebuttal of the same statement:

#include <stdio.h>

int main(int argc, char **argv)
{
while (argc-- > 0) puts(*argv++);
return 0;
}

At the end of the loop, the initial values of argc and argv are
entirely irrelevant, so there is no *good* (i.e. non-religious) reason
for preserving them.

And although this is a trivial example, it is typical for code parsing
its command line arguments. See also the example at page 117 in K&R2.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #7
Dan Pop <Da*****@cern.c h> scribbled the following:
In <Xn************ **************@ 212.27.42.74> Emmanuel Delahaye <em**********@n oos.fr> writes:
In 'comp.lang.c', Case <no@no.no> wrote:
Modifiying the value of a parameter is often the indication of a bad
design.

I'm interested in your thoughts behind this statement.
Like most such statements made by Emmanuel, it's a matter of pure
religion taken as fact.


As it stands, I happen to agree with him. Emphasis on "often the
indication of" bit. There are legitimate causes for modifying the value
of a parameter but usually it's a sign of the programmer not
understanding how C's parameter passing works.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"There's no business like slow business."
- Tailgunner
Nov 14 '05 #8
In 'comp.lang.c', Da*****@cern.ch (Dan Pop) wrote:
Like most such statements made by Emmanuel, it's a matter of pure
religion taken as fact.
I was naively thinking that Usenet was not the place for nominative attacks.
Sounds that I was wrong. My statements belong to my coding guidelines that
result from a rather long experience in C-programming. You may gently agree
or not, byt why being so harsh ?
The code given by the original poster is a perfect illustration of this
statement.


And the following code is a perfect rebuttal of the same statement:

#include <stdio.h>

int main(int argc, char **argv)
{
while (argc-- > 0) puts(*argv++);
return 0;
}

At the end of the loop, the initial values of argc and argv are
entirely irrelevant, so there is no *good* (i.e. non-religious) reason
for preserving them.


What a strange example. What if I now want to access to the arguments ? Or to
check the number of arguments?

Your example illustrates exactly what I try to fight against : the
destruction of the initial value of a parameter.
And although this is a trivial example, it is typical for code parsing
its command line arguments. See also the example at page 117 in K&R2.


I think that I'm not the one that consider the K&R2 a Sacred Book. Who is the
one with a religious attitude ?

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #9
Dan Pop wrote:
In <Xn************ **************@ 212.27.42.74> Emmanuel Delahaye <em**********@n oos.fr> writes:
In 'comp.lang.c', Case <no@no.no> wrote:
Modifiying the value of a parameter is often the indication of a bad
design.

I'm interested in your thoughts behind this statement.


Like most such statements made by Emmanuel, it's a matter of pure
religion taken as fact.
The code given by the original poster is a perfect illustration of this
statement.


And the following code is a perfect rebuttal of the same statement:

#include <stdio.h>

int main(int argc, char **argv)
{
while (argc-- > 0) puts(*argv++);
return 0;
}

At the end of the loop, the initial values of argc and argv are
entirely irrelevant, so there is no *good* (i.e. non-religious) reason
for preserving them.


Appreciated.

- Dario
Nov 14 '05 #10

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

Similar topics

13
5740
by: Michael B Allen | last post by:
Hi, I've tried to write the *simplest* memory allocator possible. I think it would be useful in many cases such as allocating memory on stack as a poor man's garbage collection perhaps. I was hoping the clc crowd had some ideas for making it even simpler! In-lined below the full program (132 lines). It's a circular singular linked list of "cells" inspired by the one in Plauger's text
13
4121
by: na1paj | last post by:
here's a simple linked list program. the DeleteNode function is producing an infinit loop i think, but i can't figure out where.. #include <stdio.h> typedef struct { char *str; //str is a dynamic array of characters int length; //number of characters } String;
6
2516
by: Nick | last post by:
excuse me!! may i ask a simple problem here? if i dynamically allocate a memory(ex. new in C++ or malloc in C) in a sub-function and forget free the space end of the sub-function. does it cause memory leak or the space automatically free by OS??
51
8285
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
0
362
by: Greg | last post by:
I am continuing writing my simple file system and I have run across the following problem. I am writing a superblock to a certain frame in the file as follows: (&sb is the address of a superblock struct with size < FRAME_SZ * 4) #define FRAME_SZ 512 int frame = 3 ;
9
1632
by: Valerio Daelli | last post by:
Hello everybody I have a problem with a linked list. I just get segmentation faults. Could anyone please help me? Thanks, this is the code __________________________ #include <stdio.h> #include <stdlib.h>
8
5112
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
6
3667
by: sathyashrayan | last post by:
#include<stdio.h> #include<stdlib.h> #include<string.h> struct tree { int data; struct tree *left,*right; }; void init(struct tree *node)
9
2047
by: robbie.carlton | last post by:
Hello! I've programmed in c a bit, but nothing very complicated. I've just come back to it after a long sojourn in the lands of functional programming and am completely stumped on a very simple function I'm trying to write. I'm writing a function that takes a string, and returns an array of strings which are the result of splitting the input on whitespace and parentheses (but the parentheses should also be included in the array as...
0
9456
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
9275
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
9873
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
9846
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
6534
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
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3806
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
3359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
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.