473,770 Members | 2,630 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read dynamic string

I use this code to read dynamic string:

char *s1;
.......
puts("Inserire una stringa: ");
while((*s1++=ge tchar())!='\n') ;
*s1='\0';

The compilation (ANSI C) is OK but I receive an error during the execution.

The problem is not present if I use a static array.

I cannot find the error.
Nov 26 '05 #1
24 2405

"Sillaba atona" <NO****@tin.i t> wrote in message
char *s1;
......
puts("Inserire una stringa: ");
while((*s1++=ge tchar())!='\n') ;
*s1='\0';

The compilation (ANSI C) is OK but I receive an error during the
execution.

The problem is not present if I use a static array.

I cannot find the error.

s1 points to nowhere in particular. You then start overwriting this random
memory location with characters. Usually the result will be a crash
(probably a message saying "segmentati on fault").
If you say s1 = malloc(1000) then s1 will point to 1000 chars reserved for
you, and the program won't crash until you exceed that figure. (You can keep
a count and call realloc(), if you want to be able to read an arbitrary
string as long as the computer's meory allows).
Nov 26 '05 #2
In article <43************ ***********@rea der1.news.tin.i t>,
Sillaba atona <NO****@tin.i t> wrote:
I use this code to read dynamic string: char *s1;
......
puts("Inseri re una stringa: ");
while((*s1++=g etchar())!='\n' );
You have not allocated any storage. s1 is an uninitialized pointer;
you have to point it to a block of memory before you can use that code.

Except that that code doesn't take into account the possibility of
a really long string, and if you pre-allocate the memory then no matter
how much you allocate, the user might enter something larger.
Therefore you either need to limit the length that you will pay
attention to, or else you need to use a scheme in which the allocated
memory is grown as needed.
*s1='\0'; The compilation (ANSI C) is OK but I receive an error during the execution.
A good compiler would warn that s1 was potentially uninitialized, but
such a warning is not -required- by the standard.
The problem is not present if I use a static array.


Change back to a static, and then have the user paste in (say)
32K of text, and see whether you still say the problem is "not present"
when you use a static array.
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Nov 26 '05 #3
Malcolm wrote:
If you say s1 = malloc(1000) then s1 will point to 1000 chars reserved for
you, and the program won't crash until you exceed that figure. (You can keep
a count and call realloc(), if you want to be able to read an arbitrary
string as long as the computer's meory allows).


Or you can keep reading into unallocated buffer until your computer meows.

;-)

with respect,
Toni Uusitalo
Nov 26 '05 #4
Hi,
(You can keep a count and call realloc(), if you want to be able to read
an arbitrary string as long as the computer's meory allows).


there's also a neat way that involves using recursion to allocate
additional memory on the stack and putting the parts together on return,
thereby avoiding heap fragmentation.
Daniel

Nov 26 '05 #5
Sillaba atona <NO****@tin.i t> wrote:
char *s1;
......
puts("Inserire una stringa: ");
while((*s1++=ge tchar())!='\n') ;
*s1='\0'; The compilation (ANSI C) is OK but I receive an error during the execution.


It's wrong, as others have indicated.

You might find Chuck Falconer's ggets() routine, available at
cbfalconer.home .att.net/download/ggets.zip, to be helpful. Chuck is
(or at least was, he seems to have been missing for some time) a
regular contributor here, so you can use the code with confidence
(per the license, which I believe is GPL).

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 27 '05 #6

"Daniel Fischer" <sp**@erinye.co m> wrote
(You can keep a count and call realloc(), if you want to be able to read
an arbitrary string as long as the computer's meory allows).


there's also a neat way that involves using recursion to allocate
additional memory on the stack and putting the parts together on return,
thereby avoiding heap fragmentation.

Could you post a getline() function (get a line from a file, of arbitrary
length) that uses this?
Nov 27 '05 #7
Daniel Fischer wrote:
Hi,

(You can keep a count and call realloc(), if you want to be able to read
an arbitrary string as long as the computer's meory allows).

there's also a neat way that involves using recursion to allocate
additional memory on the stack and putting the parts together on return,
thereby avoiding heap fragmentation.


This is possible but I doubt it's worth the hassle (I admit it sounds
like neat trick).

I think something that reuses existing buffer would be enough for
avoiding constant buffer fiddling/reallocating.

Something like this:

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

struct GetLine {
FILE *f;
char *buf;
size_t bufsize;
};

int GetLine_Init(st ruct GetLine *gl, FILE *f)
{
gl->f = f;
gl->bufsize = 256;
gl->buf = malloc(gl->bufsize);
return (gl->buf) ? 1 : 0;
}

void GetLine_Destroy (struct GetLine *gl)
{
free(gl->buf);
}

char *GetLine_Read(s truct GetLine *gl)
{
size_t i=0;
int ch;

while(gl->buf) {
for(; i<gl->bufsize; gl->buf[i++]=ch) {
ch = fgetc(gl->f);
if (ch == EOF || ch == '\n') {
if (!i && ch == EOF) return NULL;
gl->buf[i] = '\0';
return gl->buf;
}
}
gl->bufsize += gl->bufsize;
gl->buf = realloc(gl->buf, gl->bufsize);
}
return NULL;
}

int main(int argc, char* argv[])
{
struct GetLine gl;
char *line;
FILE *f = fopen("test.txt ", "r");

if (!f) return (EXIT_FAILURE);
if (!GetLine_Init( &gl, f)) return (EXIT_FAILURE);

while((line=Get Line_Read(&gl)) )
puts(line);

GetLine_Destroy (&gl);
fclose(f);
return 0;
}

with respect,
Toni Uusitalo

Nov 27 '05 #8
Daniel Fischer wrote:
Hi,

(You can keep a count and call realloc(), if you want to be able to read
an arbitrary string as long as the computer's meory allows).

there's also a neat way that involves using recursion to allocate
additional memory on the stack and putting the parts together on return,
thereby avoiding heap fragmentation.
Daniel

I'd love to see that. Can you post the code?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 27 '05 #9
On Sun, 27 Nov 2005 18:27:12 -0500, Joe Wright wrote:
there's also a neat way that involves using recursion to allocate
additional memory on the stack and putting the parts together on return,
thereby avoiding heap fragmentation.
Daniel

I'd love to see that. Can you post the code?


Sure:

------------------------->8---------------------------

/*
* rfgets.c
* dynamically allocating fgets
* daniel.fischer at iitb.fraunhofer .de
*/

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

char *rfg(FILE * f, int l) {
char b[32], *p;
int x;

if(!fgets(b, sizeof(b), f)) return 0;
x = strlen(b);
if(b[x - 1] != '\n' && (p = rfg(f, l + x))) {
p -= x;
memcpy(p, b, x);
return p;
}
p = (char *) malloc(l + x + 1) + l;
strcpy(p, b);
return p;
}

char *rfgets(FILE * f) {
return rfg(f, 0);
}

------------------------->8---------------------------

Usage:

char *line = rfgets(stdin);
...
free(line); // don't forget
Daniel

Nov 28 '05 #10

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

Similar topics

14
2245
by: Spare Change | last post by:
I am told that I can have a dynamic or static string array. So if I declare string dynamic; How do I add elements to dynamic and resize it ?
22
13333
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; char c; std::string str;
0
3517
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list boxes do not necessarily need to have a selection made to be used in the dynamic query. In essence the form can have selections made in all or none of its list boxes to form the dynamic query I am looking to get some feedback in reference to...
10
10250
by: Xinyi Yang | last post by:
Hi, I have to read information out of a file. The format will be string1,string2,..., string3,string4,..., .... (the string sould not contain ' ' anyway) the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first...
6
2981
by: Materialised | last post by:
Hi Everyone, I apologise if this is covered in the FAQ, I did look, but nothing actually stood out to me as being relative to my subject. I want to create a 2 dimensional array, a 'array of strings'. I already know that no individual string will be longer than 50 characters. I just don't know before run time how many elements of the array will be needed. I have heard it is possible to dynamically allocate memory for a 2
5
3760
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...
7
22497
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...
2
3639
by: Luis Arvayo | last post by:
Hi, In c#, I need to dynamically create types at runtime that will consist of the following: - inherits from a given interface - will have a constructor with an int argument
14
1623
by: dascandy | last post by:
Hi, I was wondering, is it possible to determine whether a string can be modified (const char *) by the application or whether it's located in what's commonly .rodata? Regards, Peter
0
9602
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
9439
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
10237
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
10071
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...
1
10017
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
8905
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...
0
5326
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
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2832
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.