473,405 Members | 2,185 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.

Dynamic Memory Allocation for Reading String

Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */
char *s; /* string being read */

f = "somefile.txt";
s = malloc(sizeof(char*)); /* allocates mem of string */
while( fscanf(f, "%s", s) != EOF )
{ /* read from FILE */
realloc(s, strlen(s)+1); /* reallocate that mem */
foo(s) /* do something with s */
}
free(s);

When complied, I get a segmentation error which means my allocation is
invalid somewhere. Please take a look and provide any comments.
Thanks.

Nov 15 '05 #1
6 3387
dough wrote:
Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */
char *s; /* string being read */

f = "somefile.txt";
s = malloc(sizeof(char*)); /* allocates mem of string */
The line above makes no sense. There is no reason to suppose that an
area the size of a pointer to char is useful at all, especially when while( fscanf(f, "%s", s) != EOF ) tries to cram a string of unknown length into such a tiny space.
The use of fscanf is unlikely to be a good idea here, even when
reasonable choices for the argument to malloc.
{ /* read from FILE */
realloc(s, strlen(s)+1); /* reallocate that mem */
The above line seems to be based on a fundamental contradiction. It
assumes that a string has been properly read via fscanf. Unless that
string is shorter than the space allocated for s -- very unlikely since
s was allocated a very tiny space to start with -- this reallocation
would imply that s is being given needed space for the string which it
already had space for.
foo(s) /* do something with s */
}
free(s);

When complied, I get a segmentation error which means my allocation is
invalid somewhere.
Obviously.
Please take a look and provide any comments.
Thanks.

Nov 15 '05 #2
dough wrote:
Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */
char *s; /* string being read */

f = "somefile.txt";
s = malloc(sizeof(char*)); /* allocates mem of string */
It doesn't do what you want it to do. It allocates space for an object
whose size equals `sizeof(char *)'. So, if sizeof(char *) on your
system is 4, you can store a string with a maximum of 3 characters
and no more.

Since you want to store a
string allocate enough room for the biggest string that you might
find in the file, add one for the terminating
'\0' and do something like:
#define MAXSTRSIZE 30
...
s = malloc( MAXSTRSIZE + 1 )
while( fscanf(f, "%s", s) != EOF )
{ /* read from FILE */
realloc(s, strlen(s)+1); /* reallocate that mem */
Why would you want this?

[ ...] When complied, I get a segmentation error which means my allocation is
invalid somewhere.


Yes, that's possible, as there's probably not enough room for the
string
you read in, and a access-out-of-bounds happens. And BOOM!

Nov 15 '05 #3
"dough" <vi****@gmail.com> writes:
Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */
char *s; /* string being read */

f = "somefile.txt";
s = malloc(sizeof(char*)); /* allocates mem of string */
while( fscanf(f, "%s", s) != EOF )
{ /* read from FILE */
realloc(s, strlen(s)+1); /* reallocate that mem */
foo(s) /* do something with s */
}
free(s);

When complied, I get a segmentation error which means my allocation is
invalid somewhere. Please take a look and provide any comments.
Thanks.


Please post real compilable code.

The statement
f = "somefile.txt";
makes no sense; probably your real code uses fopen().

The statement
s = malloc(sizeof(char*));
allocates enough space for a pointer-to-char; it doesn't allocate
space for the string it pointes to.

The call
fscanf(f, "%s", s)
is unsafe. The "%s" format matches a sequence of non-whitespace
characters; it doesn't specify the maximum length, so there's no way
to guard against overflowing the allocated buffer. (Do you want to
read sequences of non-whitespace character, or entire lines?)

You don't capture the result of realloc(), but by the time you call it
it's probably too late; chances are you've already overflowed your
buffer.

Again, post your actual code, not a summary.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #4
dough wrote:
Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */
char *s; /* string being read */

f = "somefile.txt";
f = fopen("somefile.txt","r");
s = malloc(sizeof(char*)); /* allocates mem of string */
You're getting the size of a pointer why? s is going to be a very short
string.
while( fscanf(f, "%s", s) != EOF )
I don't see why you fscanf to get a string. Why not use fgets()?
*scanf() is mostly useful for parsing out numbers, or complex
combinations, for instance:

sscanf(timestamp, "%d:%d:%d - %s",hour,minute,second,message)

or something like that.
{ /* read from FILE */
realloc(s, strlen(s)+1); /* reallocate that mem */
You're increasing s by one byte every time. Is each line one character
longer than the last?
foo(s) /* do something with s */
}
free(s);

When complied, I get a segmentation error which means my allocation is
invalid somewhere.
Actually, it can mean any number of things. It will either be with your
odd use of allocation or your string instead of FILE for input. (I'd
guess the latter.)
Please take a look and provide any comments.
Thanks.

I don't see why you're dynamically allocating in the first place.
You're only using one string, so there's no great need for malloc().

Pick a number that's at least a little bit larger (2 bytes, for the
\n\0 sequence) than the longest line you could possibly expect in your
file, and just use that. Unless you've got a function to predict how
many characters it's going to be, there's no way to allocate
intelligently without first having the string.

Nov 15 '05 #5
"Chris Johnson" <ef******@gmail.com> wrote in news:1128401860.308575.60000
@g14g2000cwa.googlegroups.com:
Pick a number that's at least a little bit larger (2 bytes, for the
\n\0 sequence) than the longest line you could possibly expect in your
file,


And, one day, the program will have to read a file that is slightly larger
than the largest size you expected.

Starting with a buffer of given size, reading chunks of input, and
realloc'ing as necessary would be a proper strategy for reading input of
unknown size.

Sinan

--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
Nov 15 '05 #6
Keith Thompson wrote:
"dough" <vi****@gmail.com> writes:
Heres a snippet of my code. I am trying to dynamically allocate memory
for reading in strings from a file.

FILE *f; /* file to read */

f = "somefile.txt";
<snip> Please post real compilable code.

The statement
f = "somefile.txt";
makes no sense; probably your real code uses fopen().

<snip>

Compiles on my system. >:-) Of course, the compiler is kind enough to
issue a warning...

S.
Nov 15 '05 #7

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

Similar topics

5
by: meyousikmann | last post by:
I am having a little trouble with dynamic memory allocation. I am trying to read a text file and put the contents into a dynamic array. I know I can use vectors to make this easier, but it has to...
6
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory...
11
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
8
by: omariqbalnaru | last post by:
Is there anyway to allocate memory dynamically according to the input? For example if the user has to input his name e.g. in this case Omar Iqbal Naru is inputted by the user. How to allocate...
24
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array...
1
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was...
18
by: welch.ryan | last post by:
Hi all, Having a problem with addressing large amounts of memory. I have a simple piece of code here that is meant to allocate a large piece of memory on a ppc64 machine. The code is: /*...
14
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
4
bobbi2004
by: bobbi2004 | last post by:
Well, thank you for reading this question . Any answers or ideas are very appreciated . I am new in C and i have a proplem . I want to write a program that accept some strings from the users , i...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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...
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,...
0
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...

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.