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

malloc for strings(beginner)

Dear group,
if I want to allocate a string with a help of malloc then, shall
I use the following in a loop?
char *s;
s = malloc(strlen(s)+1);
Any pointer reference is help full. I went through the K & R
book's chapter 5. But I am not able to get the answer.
Dec 23 '06 #1
9 2184
"fool" <fo**@fool.comwrote in message
>
if I want to allocate a string with a help of malloc then, shall
I use the following in a loop?
char *s;
s = malloc(strlen(s)+1);
Any pointer reference is help full. I went through the K & R
book's chapter 5. But I am not able to get the answer.
At a guess, you are getting a string character by character, maybe from a
file.
What you want is this

char *s = 0;
char ch;
In N = 0;

do
{
ch = getacharacter();
N++;
s = realloc(s, N);
if(!s)
{
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
s[N-1] = ch;
} while(ch != 0);

Modify the code if the string is termianted by newline (you will have to
replace the last charcter by a 0).
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
Dec 23 '06 #2
Malcolm said:

<snip>
What you want is this
<snip>
s = realloc(s, N);
Never wise.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 23 '06 #3
In article <uJ******************************@bt.com>,
re*******@btinternet.com says...
"fool" <fo**@fool.comwrote in message

if I want to allocate a string with a help of malloc then, shall
I use the following in a loop?
char *s;
s = malloc(strlen(s)+1);
Any pointer reference is help full. I went through the K & R
book's chapter 5. But I am not able to get the answer.
At a guess, you are getting a string character by character, maybe from a
file.
What you want is this

char *s = 0;
char ch;
In N = 0;

do
{
ch = getacharacter();
N++;
s = realloc(s, N);
if(!s)
{
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
s[N-1] = ch;
} while(ch != 0);

Modify the code if the string is termianted by newline (you will have to
replace the last charcter by a 0).
Am I correct with the following:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch, length;
int n,i;
do
{
fgets(s, sizeof s, stdin);
n++;
s = realloc(s, n);
if(!s)
exit(EXIT_FAILURE);
ch = *s++;
s[n-1] = ch;
length = strlen(s);
}while(ch != 0 );
for(i=0 ; i < length ; i++)
printf("%c\n",s[i]);

return 0;
}

But gcc gives me a RT error.
Dec 23 '06 #4
fool said:

<snip>
>
Am I correct with the following:
No.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch, length;
int n,i;
do
{
fgets(s, sizeof s, stdin);
fgets requires a pointer to the first byte of memory it can use. But s is a
null pointer, so it doesn't point to any memory fgets can use. And the
second argument is supposed to say how many bytes of memory are available
at that address, to which the best answer you could reasonably give is: 0.

If you want to put stuff in a box, first get a box.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 23 '06 #5
In article <2r*********************@bt.com>, rj*@see.sig.invalid says...
fool said:

<snip>

Am I correct with the following:

No.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch, length;
int n,i;
do
{
fgets(s, sizeof s, stdin);

fgets requires a pointer to the first byte of memory it can use. But s is a
null pointer, so it doesn't point to any memory fgets can use. And the
second argument is supposed to say how many bytes of memory are available
at that address, to which the best answer you could reasonably give is: 0.

If you want to put stuff in a box, first get a box.
Me and my foolish brain!!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch;
int n=0;
do
{
s = realloc(s, n);
if(!s)
exit(EXIT_FAILURE);
fgets(s, sizeof s, stdin);
n++;
ch = *s;
s[n-1] = ch;
printf("%s",s);
}while(ch != 0 && (*s) != '\0'); /* derefer s and till s
reaches '\0', correct?*/
return 0;
}
Dec 23 '06 #6
fool said:

<snip>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch;
int n=0;
do
{
s = realloc(s, n);
if(!s)
exit(EXIT_FAILURE);
This is not a good idea, but it'll do for now, except for the fact that
you're allocating ZERO bytes of memory on the first time round.
fgets(s, sizeof s, stdin);
sizeof s is wrong - s has type char *, so sizeof s is equivalent to
sizeof(char *), which isn't going to change any time soon. What you should
put here instead is the number of bytes available at the memory pointed to
by s - in this case, that would be n.

What if fgets failed? (It returns NULL if it encounters an error or an
end-of-file condition.) You need to detect this.
n++;
ch = *s;
copies first character of the input string to ch
s[n-1] = ch;
copies ch to the (n-1)th character of s - is that *really* what you want to
do? Especially if it overwrites your terminating null character (which
seems possible to me, although I admit I haven't read the code very
closely).
printf("%s",s);
}while(ch != 0 && (*s) != '\0'); /* derefer s and till s
reaches '\0', correct?*/
I think you need to take a step back and decide exactly what it is that
you're trying to do. Do you just want to read one string from stdin, or
many? Do you want to store one string, or many? What are you aiming for? If
you can answer this, perhaps we can help you better.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 23 '06 #7
fool wrote:
rj*@see.sig.invalid says...
>fool said:

<snip>
>>>
Am I correct with the following:

No.
>>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch, length;
int n,i;
do
{
fgets(s, sizeof s, stdin);

fgets requires a pointer to the first byte of memory it can use.
But s is a null pointer, so it doesn't point to any memory fgets
can use. And the second argument is supposed to say how many bytes
of memory are available at that address, to which the best answer
you could reasonably give is: 0.

If you want to put stuff in a box, first get a box.

Me and my foolish brain!!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch;
int n=0;
do
{
s = realloc(s, n);
No. The very first time you are allocating 0 bytes. This can't
hold anything. In addition reallocating for each input character
is an expensive operation.
if(!s)
exit(EXIT_FAILURE);
fgets(s, sizeof s, stdin);
n++;
ch = *s;
s[n-1] = ch;
printf("%s",s);
}while(ch != 0 && (*s) != '\0'); /* derefer s and till s
reaches '\0', correct?*/
return 0;
}
Now that you have tried various things out, download ggets and see
how I handle it. You can find the complete module at:

<http://cbfalconer.home.att.net/download/>

and it will probably be quite understandable after your efforts.
Most of the download is testing code and demonstration usage. It
then adds up to a whopping 11k byte download. the reallocation
strategy is optimized for the most usual usage of interactive
input, when very long input strings are extremely rare, and usually
require keyboard walking cats.

rjh has an alternative method. See readme.txt file in ggets.zip.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

Dec 23 '06 #8
fool wrote:
In article <2r*********************@bt.com>, rj*@see.sig.invalid says...
>fool said:

<snip>
>>Am I correct with the following:
No.
>>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch, length;
int n,i;
do
{
fgets(s, sizeof s, stdin);
fgets requires a pointer to the first byte of memory it can use. But s is a
null pointer, so it doesn't point to any memory fgets can use. And the
second argument is supposed to say how many bytes of memory are available
at that address, to which the best answer you could reasonably give is: 0.

If you want to put stuff in a box, first get a box.

Me and my foolish brain!!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *s=0,ch;
int n=0;
do
{
s = realloc(s, n);
if(!s)
exit(EXIT_FAILURE);
fgets(s, sizeof s, stdin);
n++;
ch = *s;
s[n-1] = ch;
printf("%s",s);
}while(ch != 0 && (*s) != '\0'); /* derefer s and till s
reaches '\0', correct?*/
return 0;
}
Several things I don't understand about your code but here's mine.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char line[80];
char *t, *s = NULL;
int n, len = 0;
while (fgets(line, sizeof line, stdin)) {
n = strlen(line);
t = realloc(s, len + n+1);
if (!t) puts("alloc failure."), exit(EXIT_FAILURE);
s = t;
strcpy(s+len, line);
len = strlen(s);
}
printf("%s", s);
return 0;
}

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 23 '06 #9
On Sat, 23 Dec 2006 12:27:48 +0530, fool <fo**@fool.comwrote in
comp.lang.c:

There is a serious error in your concept below.
Dear group,
if I want to allocate a string with a help of malloc then, shall
I use the following in a loop?
char *s;
Assuming that the definition of s, above, is inside a function, you
have created an uninitialized pointer, that is it does not contain the
address of one or more characters that belong to your program.
s = malloc(strlen(s)+1);
Passing the uninitialized pointer value 's' so strlen(), as you will
do on the first pass through the loop, produces undefined behavior and
quite possibly will cause your operating system to shut down your
program.
Any pointer reference is help full. I went through the K & R
book's chapter 5. But I am not able to get the answer.
I am not completely sure what it is you are trying to do. You have
not shown us enough of your code. The correction is different if you
are trying to allocate memory to copy an existing string, or if you
are trying to allocate memory for a string coming from an input
stream.

You should post again, and include the complete function that you are
trying to write, with an explanation of what it's inputs are and
exactly what you want the result to be.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Dec 23 '06 #10

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

Similar topics

66
by: Knady | last post by:
Hi, I have the following problem, I must to do my assignment, but I really do not know how to use the malloc. I need create a program that will be used to do some algebrical computation on the...
6
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)
11
by: rory | last post by:
Cna anyone point me in the right direction, I have a struture in my .h file: typedef struct mdata { int names; int dates; int ages; }m_Data;
10
by: Aris | last post by:
A few days ago I asked from you how to join a string like "file" A number that change values from 1 to 5 and another string like ".txt" to have a result like "file1.txt","file2.txt" and so on ...
7
by: Marcel | last post by:
I am C++ beginner. When i start building very basic things like hello world programs i am very attired by the <string> library so i put all text things in strings. Is that good programmers...
5
by: Yourko | last post by:
Hi there! I`me currently trying to write some simple programs in C. For one such program i created globals.h file. In that file i defined a structure of type _client, and a pointer of that type: ...
9
by: raam | last post by:
hi all, I trying to write an array of integers into a text file.While writing into the file it works.I used fwrite function, but when I read the same file using fread or fscanf it fails and it...
12
by: nodrogbrown | last post by:
hi i want to create an array of strings .I know the number of items that the array will contain but the size of each string will be different and will not be known at compile time. eg: in char...
6
by: lgerhardx | last post by:
First of all, please forgive my newness to the language. I have had much experience programming...but not in C! :) I am modifying a program designed in LabWindows/CVI, which as far as I can...
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: 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...
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
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,...
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...

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.