473,803 Members | 3,625 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
18 2448
Charlie Gordon wrote:
"Karthik Kumar" <ka************ *******@yahoo.c om> wrote in message
news:41c90b47$1 @darkstar...
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 !


I used to think the same thing, but the reality is that realloc is
just too useful to discard.

It does take a modicum of care to use realloc correctly but, once
you have learned how to do it, it's actually not at all complex. Anyone
who cannot master realloc is going to struggle in their programming
career, for the simple reason that they are required to master lots
of stuff that is much, much more complex than realloc.
Nov 14 '05 #11
On Wed, 22 Dec 2004 06:50:35 +0000 (UTC)
infobahn <in******@btint ernet.com> wrote:
Karthik Kumar wrote:

<snip>

pointer to pointer could be the answer.

int main(void)
{
char *string1;
string1 = malloc(6);
You need to test to see if malloc has failed.
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.


Also, if the realloc fails you have lost your pointer to the memory you
still have allocated.

void foo(char **my_string)
{
char *tmp = realloc(*my_str ing, 12);
if (tmp == NULL) {
/* handle error */
}
else {
*my_string = tmp
}
}

I've also changed the name because identifiers starting with str
followed by another letter, such as string, are reserved.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #12


infobahn wrote:


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.

I realize that you are using the routines provided by the op, but
without too much trouble you can provide protection should the function
be called with no previous allocations, i.e. should *string == NULL.
If you do this then you need not worry with doing the initial allocation
in function main. Instead, use the function for the initial string and
subsequent appends.

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 */
}


Should *string be NULL and the allocation succeed, you would
need to assign string[0] the value of '\0' for the strcat
function to work.

Example:

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

int dCatStr(char **s, const char *catstr)
{
char *tmp;
size_t curlen = *s?strlen(*s):0 ;

if((tmp = realloc(*s,curl en+strlen(catst r)+1)) != NULL)
{
if(curlen == 0) *tmp = '\0';
*s = tmp;
strcat(*s,catst r);
}
return tmp?1:0;
}

int main(void)
{
char *string1 = NULL;

if(dCatStr(&str ing1,"Hello"))
if(dCatStr(&str ing1," World!"))
printf("string1 = \"%s\"\n",strin g1);
else puts("FAILURE: to append");
else puts("FAILURE: to append");
free(string1);
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #13
Flash Gordon wrote:
On Wed, 22 Dec 2004 06:50:35 +0000 (UTC)
infobahn <in******@btint ernet.com> wrote:

Karthik Kumar wrote:

<snip>
pointer to pointer could be the answer.

int main(void)
{
char *string1;
string1 = malloc(6);


You need to test to see if malloc has failed.


Well, Earthik Kumar does. If you glance over my
reply to the OP, you'll find that I addressed
this issue, and all the others you mentioned, except ...

<snip>
void foo(char **my_string)
{
char *tmp = realloc(*my_str ing, 12);
if (tmp == NULL) {
/* handle error */
}
else {
*my_string = tmp
}
}

I've also changed the name because identifiers starting with str
followed by another letter, such as string, are reserved.


Not local identifiers.
Nov 14 '05 #14
Al Bowers wrote:


infobahn wrote:


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.

I realize that you are using the routines provided by the op,


Right.
but
without too much trouble you can provide protection should the function
be called with no previous allocations, i.e. should *string == NULL.
If you do this then you need not worry with doing the initial allocation
in function main. Instead, use the function for the initial string and
subsequent appends.
I thought I'd squeezed all the juice out of it, but you're right - I
should have suggested this myself. Apologies for my omission.

<snip>
Example:

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

int dCatStr(char **s, const char *catstr)
{
char *tmp;


It would be profitable to add an assertion here:

assert(s != NULL);

before dereferencing s. This would of course involve including
<assert.h> and, in C90, enclosing the remainder of the code in
a block { }, or separating the definition of curlen from the
test on *s (for the obvious reason).

<snip>
Nov 14 '05 #15
infobahn wrote on 22/12/04 :
I've also changed the name because identifiers starting with str
followed by another letter, such as string, are reserved.


Not local identifiers.


Saiz who ?

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

"C is a sharp tool"

Nov 14 '05 #16
Emmanuel Delahaye wrote:
infobahn wrote on 22/12/04 :
I've also changed the name because identifiers starting with str
followed by another letter, such as string, are reserved.

Not local identifiers.

Saiz who ?


ANSI, if I'm reading the Standard correctly.

****
4.13 FUTURE LIBRARY DIRECTIONS

The following names are grouped under individual headers for
convenience. All external names described below are reserved no
matter what headers are included by the program.
****

The possibility remains that I am not reading the Standard correctly.
Nov 14 '05 #17
infobahn wrote on 23/12/04 :
Emmanuel Delahaye wrote:
infobahn wrote on 22/12/04 :
I've also changed the name because identifiers starting with str
followed by another letter, such as string, are reserved.

Not local identifiers.


Saiz who ?


ANSI, if I'm reading the Standard correctly.

****
4.13 FUTURE LIBRARY DIRECTIONS

The following names are grouped under individual headers for
convenience. All external names described below are reserved no
matter what headers are included by the program.
****

The possibility remains that I am not reading the Standard correctly.


A static (hence 'not external') function with str* (say strcmp()) will
shadow the external strcmp() from the standard library. According to
the standard, technically correct, but bad practice IMO.

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

"C is a sharp tool"

Nov 14 '05 #18
Emmanuel Delahaye wrote:

<snip>

A static (hence 'not external') function with str* (say strcmp()) will
shadow the external strcmp() from the standard library. According to the
standard, technically correct, but bad practice IMO.


Shadowing names that are already known to exist in the standard library
is, of course, not just bad practice but terrible practice.

In this case, however, no such shadowing was done. In my own code, I
avoid starting names with str*, but I saw no reason to amend the OP's
code in my own article, since I figured I'd already given him enough
to think about. :-)

Nov 14 '05 #19

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

Similar topics

3
4431
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
3764
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
2926
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
3154
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
22499
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
2259
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
1755
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
4268
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
5295
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
9700
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
9564
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
10546
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...
1
10292
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
10068
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
9121
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
7603
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...
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
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.