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

Huh ... C behavior

Copy paste and run the example now remove the comment /*test2();*/
in main function ... Its not working .. Whyyyy ?? Behavior is really
queer !!!! I know the method

"int addDynamicMemory1(char *ptr, int size)" is not the right context
of use here But I want to get the solution to this particular problem

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

void test1();
void test2();
int addDynamicMemory1(char *ptr, int size);
int addDynamicMemory(char **ptr, int size);

int addDynamicMemory1(char *ptr, int size)
{
/* See and chek whether size memory is available or not */
int currSize;
if(ptr == NULL)
{
ptr = (char*) malloc(size * sizeof(char));
if(ptr != NULL)
{
printf("Initialized memory as null \n");
return -1;
}
else
{
printf("Can not Initialized memory as null \n");
return -1;
}
}

currSize = strlen(ptr);
size = currSize + size;
ptr = (char*) realloc(ptr, size*sizeof(char));

if(ptr != NULL)
{
printf(" re Allocation size is %d\n",size);
return 0;
}

printf(" re Allocation failed \n");
return -1;
}

int addDynamicMemory(char **ptr, int size)
{
/* See and chek whether size memory is available or not */
int currSize;
if(*ptr == NULL)
{
*ptr = (char*) malloc(size * sizeof(char));
if(*ptr != NULL)
{
printf("Initialized memory as null \n");
return -1;
}
else
{
printf("Can not Initialized memory as null \n");
return -1;
}
}

currSize = strlen(*ptr);
size = currSize + size;
*ptr = (char*) realloc(*ptr, size*sizeof(char));

if(ptr != NULL)
{
printf(" re Allocation size is %d\n",size);
return 0;
}

printf(" re Allocation failed \n");
return -1;
}

int main(void)
{
test1();
/*test2();*/
}

void test2()
{
char *test = NULL;

addDynamicMemory(&test, 40);
printf("At first test value is %s\n",test);
strcpy(test,"444444444");
printf("After allocation val is %s\n", test);

addDynamicMemory1(test, 60);
strcat(test,"666666666666");
printf("After allocation val is %s\n", test);

addDynamicMemory1(test, 60);
strcat(test,"888888888888888");
printf("After allocation val is %s\n", test);
}

void test1()
{
char *test = NULL;

addDynamicMemory(&test, 40);
printf("At first test value is %s\n",test);
strcpy(test,"444444444");
printf("After allocation val is %s\n", test);

addDynamicMemory(&test, 50);
strcat(test,"5555555555");
printf("After allocation val is %s\n", test);

addDynamicMemory1(test, 60);
strcat(test,"666666666666");
printf("After allocation val is %s\n", test);

addDynamicMemory1(test, 60);
strcat(test,"888888888888888");
printf("After allocation val is %s\n", test);
}

Dec 29 '05 #1
3 1699
sa*********@gmail.com said:

<lots of stuff about dynamic allocation, which I've snipped>

It appears that the behaviour you want is as follows:

Accept a pointer to a char *, and a size.

If the pointer is NULL, return an error code. Otherwise, if the pointer
whose address was passed is NULL, allocate the supplied number of bytes.
Otherwise, assume it points to a string; find the length of that string,
assume that it represents the current allocation, and increase the
allocation by the supplied amount.

For a number of reasons, this isn't a good design, but let's run with it
anyway. Here is a simple implementation which does what I think you are
trying to do. I commend it to you for study and edification. Note
particularly the clarity and simplicity of the code, compared to your own
version.

Incidentally, I invite you to consider /why/ I said it isn't a good design.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INCSC_NO_ERROR 0
#define INCSC_BAD_ARG 1
#define INCSC_NO_MEM 2

int IncreaseStringCapacity(char **pp, size_t bytes)
{
int rc = INCSC_NO_ERROR;
char *p = NULL;
if(NULL == pp)
{
rc = INCSC_BAD_ARG;
}
else
{
if(NULL == *pp)
{
*pp = malloc(bytes);
if(NULL == *pp)
{
rc = INCSC_NO_MEM;
}
}
else
{
size_t len = strlen(*pp);
p = realloc(*pp, len + bytes + 1); /* 1 for null terminator */
if(p != NULL)
{
*pp = p;
}
else
{
rc = INCSC_NO_MEM;
}
}
}
return rc;
}

int main(int argc, char **argv)
{
char *test = NULL;
while(argc-- > 0)
{
size_t len = strlen(argv[argc]) + 2;
if(INCSC_NO_ERROR == IncreaseStringCapacity(&test, len))
{
strcat(test, "*");
strcat(test, argv[argc]);
fprintf(stdout, "String is now %s*\n", test);
}
else
{
fprintf(stderr, "Memory allocation failure.\n");
}
}
free(test);
return 0;
}

Sample run:

~/scratch> ./foo these are some command line arguments.
String is now *arguments.*
String is now *arguments.*line*
String is now *arguments.*line*command*
String is now *arguments.*line*command*some*
String is now *arguments.*line*command*some*are*
String is now *arguments.*line*command*some*are*these*
String is now *arguments.*line*command*some*are*these*./foo*
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Dec 29 '05 #2
Just changed the if .. else block .. Looks good to me. can u please
point out the bad design issues..

Thanks in advance,
Sanjay

int IncreaseStringCapacity(char **pp, size_t bytes)
{
int rc = INCSC_NO_ERROR;
char *p = NULL;
size_t len = -1;

/* if ptr2ptr string is null */
if(NULL == pp)
{
rc = INCSC_BAD_ARG;
return rc;
}

/* if str ptr has only initialized */
if(NULL == *pp)
{
*pp = malloc(bytes);
if(NULL == *pp)
{
rc = INCSC_NO_MEM;
}
return rc;
}

/* re allocating extra memory memory */
len = strlen(*pp);
p = realloc(*pp, len + bytes + 1); /* 1 for null terminator */
if(p != NULL)
{
*pp = p;
}
else
{
rc = INCSC_NO_MEM;
}

return rc;
}

Dec 29 '05 #3
sa*********@gmail.com said:
Just changed the if .. else block ..
Congratulations. You managed to make the code harder to read and harder to
maintain, for no benefit that I can see.
Looks good to me.
It looked better before.
can u please point out the bad design issues..


The code suffers from two separate, serious efficiency problems, both of
which stem directly from the design. That's all you get. Now THINK about
it, and see if you can work them out for yourself.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Dec 29 '05 #4

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

Similar topics

12
by: Dave Rahardja | last post by:
Does the C++ standard specify the behavior of floating point numbers during "exceptional" (exceptional with respect to floating point numbers, not exceptions) conditions? For example: double...
19
by: E. Robert Tisdale | last post by:
In the context of the comp.lang.c newsgroup, the term "undefined behavior" actually refers to behavior not defined by the ANSI/ISO C 9 standard. Specifically, it is *not* true that "anything can...
23
by: Ken Turkowski | last post by:
The construct (void*)(((long)ptr + 3) & ~3) worked well until now to enforce alignment of the pointer to long boundaries. However, now VC++ warns about it, undoubtedly to help things work on 64...
38
by: Steven Bethard | last post by:
> >>> aList = > >>> it = iter(aList) > >>> zip(it, it) > > That behavior is currently an accident. >http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1121416
7
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...
66
by: gyan | last post by:
Hi All, I am using sprintf and getting starnge output in following case char temp_rn; memset(temp_rn,'\0',12); sprintf(temp_rn,"0%s",temp_rn); the final value in temp_rn is 00 how it...
12
by: Rajesh S R | last post by:
Can anyone tell me what is the difference between undefined behavior and unspecified behavior? Though I've read what is given about them, in ISO standards, I'm still not able to get the...
28
by: v4vijayakumar | last post by:
#include <string> #include <iostream> using namespace std; int main() { string str; str.resize(5); str = 't';
35
by: bukzor | last post by:
I've found some bizzare behavior when using mutable values (lists, dicts, etc) as the default argument of a function. I want to get the community's feedback on this. It's easiest to explain with...
33
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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,...

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.