473,789 Members | 2,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic C String Question

I'm writing a program in C, and thus have to use C strings. The
problem that I am having is I don't know how to reallocate the space
for a C string outside the scope of that string. For example:
int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(string1);

}

void foo(char *string)
{
string = realloc(string, 12);
strcat(string, " World");
}
In this example, I reallocate the space for a string declacred in
another function in the function foo. But, after it returns to main
from the function foo, the C string will only contain "Hello". The
changes from the function foo have disappered. I suspect this is
because the reallocation has gone out of scope - and I have no idea how
to keep the changes after the function returns.
Any help would greatly be appreciated.

--Sachin

Nov 14 '05 #1
18 2446
intercom5 wrote:
I'm writing a program in C, and thus have to use C strings. The
problem that I am having is I don't know how to reallocate the space
for a C string outside the scope of that string. For example:
int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(string1);

}

void foo(char *string)
{
string = realloc(string, 12);
strcat(string, " World");
}
In this example, I reallocate the space for a string declacred in
another function in the function foo. But, after it returns to main
from the function foo, the C string will only contain "Hello". The
changes from the function foo have disappered. I suspect this is
because the reallocation has gone out of scope - and I have no idea how
to keep the changes after the function returns.


pointer to pointer could be the answer.

int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(&string1);

}

void foo(char **string)
{
*string = realloc(string, 12);
strcat(*string, " World");
}
Nov 14 '05 #2
intercom5 wrote:
I'm writing a program in C, and thus have to use C strings. The
problem that I am having is I don't know how to reallocate the space
for a C string outside the scope of that string. For example:
int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(string1);

}

void foo(char *string)
{
string = realloc(string, 12);
strcat(string, " World");
}
In this example, I reallocate the space for a string declacred in
another function in the function foo. But, after it returns to main
from the function foo, the C string will only contain "Hello". The
changes from the function foo have disappered. I suspect this is
because the reallocation has gone out of scope - and I have no idea how
to keep the changes after the function returns.


Actually the subtle change is because , realloc has moved everything
to a new address. (it is allowed to do that, of course ) because
the requested new size is > the prev. size.

OTOH, if you had requested less than the original size,
then it may not move it and just reallocate memory.
In that case, the original pointer might be still valid
after the function returns.

realloc is a multi-edged sword, indeed :) . Use it with care.
Nov 14 '05 #3


intercom5 wrote:
I'm writing a program in C, and thus have to use C strings. The
problem that I am having is I don't know how to reallocate the space
for a C string outside the scope of that string. For example:
int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(string1);

}

void foo(char *string)
{
string = realloc(string, 12); /* Where did u get this magic 12 ? not a good practise. */
strcat(string, " World");
} Always check for return values of *alloc functions.
Return the string from foo !
Modified version is:

char *foo (char *string)
{
string = realloc(string, 12);
if (string)
strcat(string, " World");

return string;
}
int main(void)
{
char *string1;
string1 = malloc(6);
if (!string1)
return 0; /* Handle failures before returning. */

sprintf(string1 , "Hello"); /* Just strcpy would do here -
strcpy(string1, "Hello"); */
string1 = foo(string1);
puts (string1);
return 0;
}


In this example, I reallocate the space for a string declacred in
another function in the function foo. But, after it returns to main
from the function foo, the C string will only contain "Hello". The
changes from the function foo have disappered. I suspect this is
because the reallocation has gone out of scope - and I have no idea how
to keep the changes after the function returns.
Any help would greatly be appreciated.

--Sachin


Nov 14 '05 #4
Karthik Kumar wrote:
pointer to pointer could be the answer.

int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(&string1);

}

void foo(char **string)
{
*string = realloc(string, 12); ^
missing '*', innit? strcat(*string, " World");
}

Nov 14 '05 #5
"Karthik Kumar" <ka************ *******@yahoo.c om> wrote in message
news:41c90b47$1 @darkstar...
Actually the subtle change is because , realloc has moved everything
to a new address. (it is allowed to do that, of course ) because
the requested new size is > the prev. size.
It is allowed to do that in all cases !
OTOH, if you had requested less than the original size,
then it may not move it and just reallocate memory.
In that case, the original pointer might be still valid
after the function returns.
don't rely in this : C99 just hints that the new and old pointers may be the
same, but they may also be different, even if the size doesn't change or if it
is reduced.
realloc is a multi-edged sword, indeed :) . Use it with care.


Or even better : realloc() is too complex to use for newbies, it has an error
prone API, it is *strongly* recommended to not use it at all !

--
Chqrlie.
Nov 14 '05 #6
thanks guys. using a pointer to a pointer worked.

Nov 14 '05 #7
intercom5 wrote:
I'm writing a program in C, and thus have to use C strings. The
problem that I am having is I don't know how to reallocate the space
for a C string outside the scope of that string. For example:
int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(string1);

}

void foo(char *string)
{
string = realloc(string, 12);
Quite apart from the problem you know you have, you also have a couple
of problems you don't know you have.
strcat(string, " World");
}
In this example, I reallocate the space for a string declacred in
another function in the function foo. But, after it returns to main
from the function foo, the C string will only contain "Hello". The
changes from the function foo have disappered. I suspect this is
because the reallocation has gone out of scope - and I have no idea how
to keep the changes after the function returns.
Any help would greatly be appreciated.


If you want a function to update a value in an object available to
the calling function, you pass that object's address to the
function. Now, in this case your object is called string1. It
happens to be a pointer, but that doesn't make it special. If you
want foo() to alter the value of string1, you must pass string1's
address to foo().

The following code is based heavily on your own code; I have changed
the indentation to make it more readable to others, and added error
checking, but I haven't "fixed" the code to my own style and preference,
tempting though the idea was.

#include <stdio.h> /* 1 */
#include <stdlib.h> /* 2 */

int foo(char **); /* 3 */

int main(void)
{
char *string1;
string1 = malloc(6);
if(string1 != NULL) /* 4 */
{
sprintf(string1 , "%s", "Hello"); /* 5 */
if(foo(&string1 ) == 0) /* 6 */
{
printf("%s\n", string1);
}
free(string1); /* 7 */
}

return 0; /* 8 */
}

int foo(char **string) /* 9 */
{
char *p = realloc(*string , 12); /* 10 */
if(p != NULL) /* 11 */
{
*string = p; /* 12 */
strcat(*string, " World"); /* 13 */
}
return p == NULL; /* 14 */
}

Notes

1. Prototype for sprintf (and a printf I added myself).
2. Prototype for malloc and free.
3. Prototype for foo. Note the change in return type,
as well as the change in arg type.
4. After a resource request, check that the request
succeeded instead of just assuming it did.
5. When sprintfing, bear in mind that your data may
contain formatting characters relevant to sprintf
(e.g. %). To avoid this from causing alarming
problems, always specify a format string.
6. Pass the ADDRESS of string1 to foo, and CHECK
the return value.
7. When you've finished with a resource, give it back.
8. main() returns int, so return an int from main().
9. We need to update a pointer and have that change
"stick", so we accept a pointer to the pointer.
10. Note the use of the temporary object p. This
temporary object can catch the return value from
realloc. If realloc fails, p will be NULL, but
*string will remain unchanged, so we at least
can still use the memory we started with.
Also note the use of *string rather than string.
11. See note 4.
12. If the request succeeded, we can (and indeed
MUST) update *string with the new value; the
old value may no longer valid and should not
be used. (If it /is/ still valid, then p == *string
anyway, but there's no way to test for this
without using *string's value, which - as I said -
may not be valid!)
13. Note again the use of *string.
14. This function needs some way of communicating to
its caller whether the allocation request succeeded
or not. An easy way to do this is via an int
return value (here, I chose 0 == success, non-0
== failure).

Sorry for the long reply. HTH. HAND.
Nov 14 '05 #8
Karthik Kumar wrote:

<snip>

pointer to pointer could be the answer.

int main(void)
{
char *string1;
string1 = malloc(6);
sprintf(string1 , "Hello");
foo(&string1);

}

void foo(char **string)
{
*string = realloc(string, 12);


This won't work. You meant:

*string = realloc(*string , 12);

Had you tested your code before posting, you'd have discovered this.

Nov 14 '05 #9
Karthik Kumar wrote on 22/12/04 :
void foo(char **string)
{
*string = realloc(string, 12);


*string = realloc(*string , 12);

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

Nov 14 '05 #10

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

Similar topics

3
4429
by: Peter Bailey | last post by:
Could someone please tell me how to pass criteria as if it were a parameter. I have a routine now that creates the sql string (well almost). at present the parameter is so I can pass one item ie Module M10S. Want I want to do is send 1 or more parameters ie M10S OR M10SA OR ...... The query works with one parameter can I send the dynamic sql from vba as a complete parameter string once the form calls the query? also I notice the...
3
6832
by: MikeY | last post by:
Hi Everyone, I am working in C#, windows forms.My question is this. All my button dynamic controls properties are present and accounted for except for the"FlatStyle" properties. I can't seem to figure out, if there is a way of using polymorphic way (if that is a word) of doing this particular property. A sample of my code is as follows: DynamicControls.ButtonControl(this,btnSearchByName, new Point(5, 75), new Size(95, 20),...
5
3762
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I believe the problem centers around my handling of strings, arrays, pointers and dynamic memory allocation. Here is the problem I'm trying to solve: I want to fill a list box with a list of Project Names from a database (in Palm this is more...
6
2924
by: MikeY | last post by:
Hi Everyone, Does anyone know where I can get my hands on a sample with source code of a simple dynamic button control in C# Windows form. I am looking for a sample that uses a class library that sets the properties send/passed from the main windows form. I'm having problems with the class library, the button control collection and my referencing it ie this.Control.Add(aControl);. Any and all help is appreciated. Thanks in advance.
1
3153
by: sleigh | last post by:
Hello, I'm building a web application that will build a dynamic form based upon questions in a database. This form will have several different sections that consist of a panel containing one to many questions. To keep it simple, I'll describe the basics of what I'm trying to design. I've created a TextBox composite control that consists of a label for
7
22498
by: Mike Livenspargar | last post by:
We have an application converted from v1.1 Framework to v2.0. The executable references a class library which in turn has a web reference. The web reference 'URL Behavior' is set to dynamic. We added an entry to the executable's .exe.config file to specify the URL, and under the 1.1 framework this worked well. Unfortunately, this is not working under the 2.0 framework. I see in the Reference.cs file under the web service reference the...
8
2257
by: Sandy Pittendrigh | last post by:
I have a how-to-do-it manual like site, related to fishing. I want to add a new interactive question/comment feature to each instructional page on the site. I want (registered) users to be able to add comments at the bottom of each page, similar to the way the php, mysql, apache manuals work. PUNCHLINE_A:
3
1754
by: topmind | last post by:
I am generally new to dot.net, coming from "scriptish" web languages such as ColdFusion and Php. I have a few questions if you don't mind. First, how does one go about inserting dynamic SQL during run-time without lots of quotes? For example, adding "AND" clauses that may or may not be present based on the query criteria form. Some of the asp.net examples use the one-line append approach which
2
4267
by: =?Utf-8?B?SmFtZXMgUGFnZQ==?= | last post by:
I’m trying to create a dynamic asp.net 2.0 siteMapPath control (using VB.net). Using the xml sitemap I’ve got these three pages: productGroup.aspx productListing.aspx productDetail.aspx Each page receives a query string i.e. productGroup.aspx?id=9 The page then renders with the appropriate details which have been accessed
0
5293
by: Eniac | last post by:
Hi, I've been working on a custom user control that needs to be modified and the validation is causing me headaches. The control used to generate a table of 4 rows x 7 columns to display all the days in the week with dates and textboxes to fill in some data. row 1: question
0
9666
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
10408
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
10199
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
9983
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
6769
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
5417
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...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4092
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
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.