fgets loop only works properly if string is malloc'd again at the end of the loopPreviously stored strings are overwritten by fgetsWhat's the rationale for null terminated strings?Good practice to free malloc's at program conclusion?malloc and scopeStrtok - reading empty string at end of linesplicing cstrings with strtok, only works on first execution of loopC - fgets() - What if the string is longer?STDIN redirection: how to make program end once fgets() reads an expected ending lineFreeing a 2D array of malloc'd strings fails in CPreviously stored strings are overwritten by fgetsusing fgets() to extract lines from a file not working
Does the Reduce option from the Enlarge/Reduce spell cause a critical hit to do 2d4 less damage?
Cooking Scrambled Eggs ends up with excess liquid
How to force GCC to assume that a floating-point expression is non-negative?
What are the IPSE’s, the ASPE’s, the FRIPSE’s and the GRIPSE’s?
If I said I had $100 when asked, but I actually had $200, would I be lying by omission?
The term Feed-forward and its meaning?
Why did the population of Bhutan drop by 70% between 2007 and 2008?
Is there a word or phrase that means "use other people's wifi or Internet service without consent"?
Count the number of shortest paths to n
Why did Lucius make a deal out of Buckbeak hurting Draco but not about Draco being turned into a ferret?
How do solar inverter systems easily add AC power sources together?
What is the meaning of “these lederhosen are riding up my Bundesliga”?
Book featuring a child learning from a crowdsourced AI book
GDPR: What happens to deleted contacts re-entered through imports
Why is getting a PhD considered "financially irresponsible" by some people?
Why did James Cameron decide to give Alita big eyes?
Should I use the words "pyromancy" and "necromancy" even if they don't mean what people think they do?
How to prevent a hosting company from accessing a VM's encryption keys?
Is a memoized pure function itself considered pure?
Why didn't Doc believe Marty was from the future?
Can MuseScore be used programmatically?
Notice period 60 days but I need to join in 45 days
Mathematica equivalent of a curl snippet
Poor error handling: Throw inside Finally
fgets loop only works properly if string is malloc'd again at the end of the loop
Previously stored strings are overwritten by fgetsWhat's the rationale for null terminated strings?Good practice to free malloc's at program conclusion?malloc and scopeStrtok - reading empty string at end of linesplicing cstrings with strtok, only works on first execution of loopC - fgets() - What if the string is longer?STDIN redirection: how to make program end once fgets() reads an expected ending lineFreeing a 2D array of malloc'd strings fails in CPreviously stored strings are overwritten by fgetsusing fgets() to extract lines from a file not working
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have to read in comma separated lines from a file, break down the args between that commas, and handle them accordingly. I have the following code set up to do exactly what I need:
char *string = malloc(MAX_INPUT);
char * current_parent;
char * current_child;
// while there are still lines to read from the file
while(fgets(string, BUFF_SIZE, file) != NULL)
// get the parent of a line and its first child
current_parent = trim(strtok(string, ","));
if(strcmp(current_parent, "") != 0) strcmp(current_child, "") == 0)
tree = add_child(tree, current_parent, "");
else
while(current_child != NULL)
tree = add_child(tree, current_parent, current_child);
current_child = trim(strtok(NULL, ","));
current_parent = 0;
current_child = 0;
string = (char *)malloc(MAX_INPUT);
// close the file
free(string);
fclose(file);
Example of a file:
john 1, sam 2
sam 2, ben 4, frances, sam 3
ben 4, sam 4, ben 5, nancy 2, holly
ben 5, john 2, sam 5
Whatever is before the first comma is the parent's name, and all other strings after that are its children's names.
My problem is that for whatever reason it only reads in the data properly if I malloc the string all over again at the end of the loop. In addition to this, if I try to free the memory before malloc'ing again, it doesn't work - resulting in memory leaks. I've even tried setting up the loop to just use a fixed sized string, but it still then reads in this jumbled data at the end. I've also tried manually emptying string at the end of each loop. I have a feeling that I may be overlooking something really simple but this has been driving me crazy. Let me know if I can provide anything else that would be of help. Thanks.
Edit: Not sure if this is important for anything but MAX_INPUT and BUFF_SIZE are both 1024
c malloc fgets
|
show 1 more comment
I have to read in comma separated lines from a file, break down the args between that commas, and handle them accordingly. I have the following code set up to do exactly what I need:
char *string = malloc(MAX_INPUT);
char * current_parent;
char * current_child;
// while there are still lines to read from the file
while(fgets(string, BUFF_SIZE, file) != NULL)
// get the parent of a line and its first child
current_parent = trim(strtok(string, ","));
if(strcmp(current_parent, "") != 0) strcmp(current_child, "") == 0)
tree = add_child(tree, current_parent, "");
else
while(current_child != NULL)
tree = add_child(tree, current_parent, current_child);
current_child = trim(strtok(NULL, ","));
current_parent = 0;
current_child = 0;
string = (char *)malloc(MAX_INPUT);
// close the file
free(string);
fclose(file);
Example of a file:
john 1, sam 2
sam 2, ben 4, frances, sam 3
ben 4, sam 4, ben 5, nancy 2, holly
ben 5, john 2, sam 5
Whatever is before the first comma is the parent's name, and all other strings after that are its children's names.
My problem is that for whatever reason it only reads in the data properly if I malloc the string all over again at the end of the loop. In addition to this, if I try to free the memory before malloc'ing again, it doesn't work - resulting in memory leaks. I've even tried setting up the loop to just use a fixed sized string, but it still then reads in this jumbled data at the end. I've also tried manually emptying string at the end of each loop. I have a feeling that I may be overlooking something really simple but this has been driving me crazy. Let me know if I can provide anything else that would be of help. Thanks.
Edit: Not sure if this is important for anything but MAX_INPUT and BUFF_SIZE are both 1024
c malloc fgets
What happens tocurrent_parentbehind the scenes? It might start with the same pointer value asstring, fromcurrent_parent = trim(strtok(string, ","));, but if it getsfreed thenstringis no longer any use. What doestrim()do?
– Weather Vane
Mar 27 at 20:34
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Is memory allocated intrimoradd_child?
– xing
Mar 27 at 20:55
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25
|
show 1 more comment
I have to read in comma separated lines from a file, break down the args between that commas, and handle them accordingly. I have the following code set up to do exactly what I need:
char *string = malloc(MAX_INPUT);
char * current_parent;
char * current_child;
// while there are still lines to read from the file
while(fgets(string, BUFF_SIZE, file) != NULL)
// get the parent of a line and its first child
current_parent = trim(strtok(string, ","));
if(strcmp(current_parent, "") != 0) strcmp(current_child, "") == 0)
tree = add_child(tree, current_parent, "");
else
while(current_child != NULL)
tree = add_child(tree, current_parent, current_child);
current_child = trim(strtok(NULL, ","));
current_parent = 0;
current_child = 0;
string = (char *)malloc(MAX_INPUT);
// close the file
free(string);
fclose(file);
Example of a file:
john 1, sam 2
sam 2, ben 4, frances, sam 3
ben 4, sam 4, ben 5, nancy 2, holly
ben 5, john 2, sam 5
Whatever is before the first comma is the parent's name, and all other strings after that are its children's names.
My problem is that for whatever reason it only reads in the data properly if I malloc the string all over again at the end of the loop. In addition to this, if I try to free the memory before malloc'ing again, it doesn't work - resulting in memory leaks. I've even tried setting up the loop to just use a fixed sized string, but it still then reads in this jumbled data at the end. I've also tried manually emptying string at the end of each loop. I have a feeling that I may be overlooking something really simple but this has been driving me crazy. Let me know if I can provide anything else that would be of help. Thanks.
Edit: Not sure if this is important for anything but MAX_INPUT and BUFF_SIZE are both 1024
c malloc fgets
I have to read in comma separated lines from a file, break down the args between that commas, and handle them accordingly. I have the following code set up to do exactly what I need:
char *string = malloc(MAX_INPUT);
char * current_parent;
char * current_child;
// while there are still lines to read from the file
while(fgets(string, BUFF_SIZE, file) != NULL)
// get the parent of a line and its first child
current_parent = trim(strtok(string, ","));
if(strcmp(current_parent, "") != 0) strcmp(current_child, "") == 0)
tree = add_child(tree, current_parent, "");
else
while(current_child != NULL)
tree = add_child(tree, current_parent, current_child);
current_child = trim(strtok(NULL, ","));
current_parent = 0;
current_child = 0;
string = (char *)malloc(MAX_INPUT);
// close the file
free(string);
fclose(file);
Example of a file:
john 1, sam 2
sam 2, ben 4, frances, sam 3
ben 4, sam 4, ben 5, nancy 2, holly
ben 5, john 2, sam 5
Whatever is before the first comma is the parent's name, and all other strings after that are its children's names.
My problem is that for whatever reason it only reads in the data properly if I malloc the string all over again at the end of the loop. In addition to this, if I try to free the memory before malloc'ing again, it doesn't work - resulting in memory leaks. I've even tried setting up the loop to just use a fixed sized string, but it still then reads in this jumbled data at the end. I've also tried manually emptying string at the end of each loop. I have a feeling that I may be overlooking something really simple but this has been driving me crazy. Let me know if I can provide anything else that would be of help. Thanks.
Edit: Not sure if this is important for anything but MAX_INPUT and BUFF_SIZE are both 1024
c malloc fgets
c malloc fgets
edited Mar 27 at 20:32
asked Mar 27 at 20:28
user11268507
What happens tocurrent_parentbehind the scenes? It might start with the same pointer value asstring, fromcurrent_parent = trim(strtok(string, ","));, but if it getsfreed thenstringis no longer any use. What doestrim()do?
– Weather Vane
Mar 27 at 20:34
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Is memory allocated intrimoradd_child?
– xing
Mar 27 at 20:55
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25
|
show 1 more comment
What happens tocurrent_parentbehind the scenes? It might start with the same pointer value asstring, fromcurrent_parent = trim(strtok(string, ","));, but if it getsfreed thenstringis no longer any use. What doestrim()do?
– Weather Vane
Mar 27 at 20:34
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Is memory allocated intrimoradd_child?
– xing
Mar 27 at 20:55
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25
What happens to
current_parent behind the scenes? It might start with the same pointer value as string, from current_parent = trim(strtok(string, ","));, but if it gets freed then string is no longer any use. What does trim() do?– Weather Vane
Mar 27 at 20:34
What happens to
current_parent behind the scenes? It might start with the same pointer value as string, from current_parent = trim(strtok(string, ","));, but if it gets freed then string is no longer any use. What does trim() do?– Weather Vane
Mar 27 at 20:34
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Is memory allocated in
trim or add_child?Mar 27 at 20:55
Is memory allocated in
trim or add_child?Mar 27 at 20:55
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25
|
show 1 more comment
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385915%2ffgets-loop-only-works-properly-if-string-is-mallocd-again-at-the-end-of-the-loo%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385915%2ffgets-loop-only-works-properly-if-string-is-mallocd-again-at-the-end-of-the-loo%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What happens to
current_parentbehind the scenes? It might start with the same pointer value asstring, fromcurrent_parent = trim(strtok(string, ","));, but if it getsfreed thenstringis no longer any use. What doestrim()do?– Weather Vane
Mar 27 at 20:34
@WeatherVane it isn't freed anywhere behind the scenes and it isn't manipulated at all aside from that line
– user11268507
Mar 27 at 20:46
Suspect damage somewhere else in the program, perhaps use a memory usage tool. How does it work if you remove all the tree operations and just print the strings extracted?
– Weather Vane
Mar 27 at 20:47
Is memory allocated in
trimoradd_child?– xing
Mar 27 at 20:55
My crystal ball tells me that you are not putting the strings into the tree, only pointers to the string, which you then overwrite with the next line.
– immibis
Mar 28 at 0:25