473,379 Members | 1,170 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,379 software developers and data experts.

malloc() and dinamic data question

Hello all!

I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:

/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concat(int, ...);

int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);
}

char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */

va_start(list, argc);
size = 0;

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}

va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}

va_end(list);

return stringstart;
}
/********** END ***********/

My questions are:

1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?

2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?

Thank you very much!

May 17 '07 #1
4 1433
On May 17, 10:24 pm, Silas Silva <sila...@gmail.comwrote:
Hello all!

I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:

/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concat(int, ...);

int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);

}

char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */

va_start(list, argc);
size = 0;

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}

va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}

va_end(list);

return stringstart;}

/********** END ***********/

My questions are:

1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?
This creates burden the function caller to pass number of arguments to
the function. If this is supposed to be a reusable module then API
user might landup in a soup if he gives different number of arguments.
Worst the caller can make you run the first loop more than required. I
dont know about internals of va_* but it might make your code
vulnerable and messy.
>
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?
the allocation of memory is wrong it should be: malloc (sizeof(char) *
size)
The calculation of size should have one more character i.e.: size +=
strlen(arg) + 1; as one NULL character's space is needed at the end
Thank you very much!

May 17 '07 #2

"quarkLore" <ag*************@gmail.comwrote in message
news:11*********************@o5g2000hsb.googlegrou ps.com...
On May 17, 10:24 pm, Silas Silva <sila...@gmail.comwrote:
>Hello all!

I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:

/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concat(int, ...);

int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);

}

char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */

va_start(list, argc);
size = 0;

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}

va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}

va_end(list);

return stringstart;}

/********** END ***********/

My questions are:

1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?
Yes.
>
<snip>
>>
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?

the allocation of memory is wrong it should be: malloc (sizeof(char) *
size)
Allocation is wrong, but not because of the above since
sizeof (*string) == sizeof (char).
The calculation of size should have one more character i.e.: size +=
strlen(arg) + 1; as one NULL character's space is needed at the end
Only one extra byte needs to be allocated, i.e.

stringstart = string = malloc(size * sizeof(*string) + 1);

Using memcpy should be faster than strcpy. To do this you would have to
remember the string lengths as you calculate them in the first loop, and
nul-terminate the string after copying. This will also save you one call to
strlen() for each string. The down side is of course that you need to
allocate memory dynamically to hold the string lengths.

--
Jonas
May 17 '07 #3
On 2007-05-17, Silas Silva <si*****@gmail.comwrote:
Hello all!

I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:

/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concat(int, ...);

int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);
}

char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */

va_start(list, argc);
size = 0;

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}

va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));

for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}

va_end(list);

return stringstart;
}
/********** END ***********/

My questions are:

1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?
Another approach is to use a special argument value to indicate that
there are no more arguments, as in

printf("%s\n", concat("foo ", "bar ", "mubble", (char *)0));

The concat function would be defined as

concat(char *arg1, ...)

and the loops over the arguments would be

va_start(list, arg1);
for(arg=arg1; arg != 0; arg=va_arg(list, char*)) {
}
va_end(list);
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?
As others have mentioned, you need to add 1 to the malloc size so
there is room for the terminating NUL character.
May 17 '07 #4
Silas Silva <si*****@gmail.comwrote:
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?
An alternative, which is easier to code but perhaps (probably?) less
efficient, is to use realloc() to grow the allocated space in steps
for each argument.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
May 18 '07 #5

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

Similar topics

4
by: raulgz | last post by:
hi I need generate dinamic sql: I need a select sentence with all fields of one table 't1' and all fields of tables which 't1' have foreings keys 't1 ( reflexive ) ,t2,t3,...' Now, l have de...
1
by: dddddd | last post by:
i need do create simple dinamic site - built mainly of pictures(they are the only dinamic part). pictuers differ by the -Location- and by -Time- (in which they were taken)... so on the index...
6
by: gp | last post by:
Hi all, I'm using Microsoft Visual C++ 6.0, I would like to see, debugging my project, all the elements of my dinamic objects.... I have a dinamic array and a STL vector and I need to know...
23
by: puzzlecracker | last post by:
Why is "new" a C++ language-level construct while "malloc" is a library function?
13
by: ppateel | last post by:
Hi, I am new to c++ and I am converting a c program to c++. I changed malloc call to new and I am getting an exception violation. Here is the relevant piece of code. Compiler vc++ 7.0 (.Net...
10
by: javuchi | last post by:
I just want to share some code with you, and have some comments and improvements if you want. This header file allocates and add and delete items of any kind of data from a very fast array: ...
25
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....
17
by: Christopher Benson-Manica | last post by:
Some recent posts got me thinking about how one might have dealt with simplistic malloc() implementations which might return NULL for a 64K request but might accept two 32K requests or four 16K...
11
by: The Doctor | last post by:
Hey people, I have a really weird problem. I am developing a string class, just for fun. I am also writing an application, which uses the string class, and uses a lot of them. But, after about...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.