Program crashed after one line input. How to fix?
I have made a program of getline function of mine. Which takes input till a 'n' is encountered and shifts to the next input. Also I have used pointer arrays here to store the string inputs, but the program crashes after the first string input. What's the problem?
This is the code of the program. I have tried to debug it but it but I can't find the problem here.
#include<stdio.h>
#include<stdlib.h>
void getline2(char *s)
{
char c;
while((c=getchar())!='n')
{
*s=c;
s++;
}
*s='';
}
int main()
{
char *lines[3];
int i=0;
while(i<3)
{
getline2(lines[i]);
i++;
}
for (i = 0; i < 3; i++)
{
printf("n%s", lines[i]);
}
return 0;
}
When I input the first line after pressing the enter the program crashes.
c pointers getline
|
show 3 more comments
I have made a program of getline function of mine. Which takes input till a 'n' is encountered and shifts to the next input. Also I have used pointer arrays here to store the string inputs, but the program crashes after the first string input. What's the problem?
This is the code of the program. I have tried to debug it but it but I can't find the problem here.
#include<stdio.h>
#include<stdlib.h>
void getline2(char *s)
{
char c;
while((c=getchar())!='n')
{
*s=c;
s++;
}
*s='';
}
int main()
{
char *lines[3];
int i=0;
while(i<3)
{
getline2(lines[i]);
i++;
}
for (i = 0; i < 3; i++)
{
printf("n%s", lines[i]);
}
return 0;
}
When I input the first line after pressing the enter the program crashes.
c pointers getline
5
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
1
Curious: who or what text suggested putting a"n"
at the start of"n%s"
?
– chux
Jan 2 at 6:52
1
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
1
If theprintf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.
– Werner Henze
Jan 2 at 7:07
1
@chux I disagree. It crashes prior to printf already. The while loop inmain
is probably noise too.getline2(lines[0])
would have sufficed to produce the crash.
– Antti Haapala
Jan 2 at 8:30
|
show 3 more comments
I have made a program of getline function of mine. Which takes input till a 'n' is encountered and shifts to the next input. Also I have used pointer arrays here to store the string inputs, but the program crashes after the first string input. What's the problem?
This is the code of the program. I have tried to debug it but it but I can't find the problem here.
#include<stdio.h>
#include<stdlib.h>
void getline2(char *s)
{
char c;
while((c=getchar())!='n')
{
*s=c;
s++;
}
*s='';
}
int main()
{
char *lines[3];
int i=0;
while(i<3)
{
getline2(lines[i]);
i++;
}
for (i = 0; i < 3; i++)
{
printf("n%s", lines[i]);
}
return 0;
}
When I input the first line after pressing the enter the program crashes.
c pointers getline
I have made a program of getline function of mine. Which takes input till a 'n' is encountered and shifts to the next input. Also I have used pointer arrays here to store the string inputs, but the program crashes after the first string input. What's the problem?
This is the code of the program. I have tried to debug it but it but I can't find the problem here.
#include<stdio.h>
#include<stdlib.h>
void getline2(char *s)
{
char c;
while((c=getchar())!='n')
{
*s=c;
s++;
}
*s='';
}
int main()
{
char *lines[3];
int i=0;
while(i<3)
{
getline2(lines[i]);
i++;
}
for (i = 0; i < 3; i++)
{
printf("n%s", lines[i]);
}
return 0;
}
When I input the first line after pressing the enter the program crashes.
c pointers getline
c pointers getline
edited Jan 2 at 7:30


Sourav Ghosh
111k15131190
111k15131190
asked Jan 2 at 6:48
theviralvtheviralv
22
22
5
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
1
Curious: who or what text suggested putting a"n"
at the start of"n%s"
?
– chux
Jan 2 at 6:52
1
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
1
If theprintf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.
– Werner Henze
Jan 2 at 7:07
1
@chux I disagree. It crashes prior to printf already. The while loop inmain
is probably noise too.getline2(lines[0])
would have sufficed to produce the crash.
– Antti Haapala
Jan 2 at 8:30
|
show 3 more comments
5
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
1
Curious: who or what text suggested putting a"n"
at the start of"n%s"
?
– chux
Jan 2 at 6:52
1
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
1
If theprintf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.
– Werner Henze
Jan 2 at 7:07
1
@chux I disagree. It crashes prior to printf already. The while loop inmain
is probably noise too.getline2(lines[0])
would have sufficed to produce the crash.
– Antti Haapala
Jan 2 at 8:30
5
5
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
1
1
Curious: who or what text suggested putting a
"n"
at the start of "n%s"
?– chux
Jan 2 at 6:52
Curious: who or what text suggested putting a
"n"
at the start of "n%s"
?– chux
Jan 2 at 6:52
1
1
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
1
1
If the
printf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.– Werner Henze
Jan 2 at 7:07
If the
printf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.– Werner Henze
Jan 2 at 7:07
1
1
@chux I disagree. It crashes prior to printf already. The while loop in
main
is probably noise too. getline2(lines[0])
would have sufficed to produce the crash.– Antti Haapala
Jan 2 at 8:30
@chux I disagree. It crashes prior to printf already. The while loop in
main
is probably noise too. getline2(lines[0])
would have sufficed to produce the crash.– Antti Haapala
Jan 2 at 8:30
|
show 3 more comments
2 Answers
2
active
oldest
votes
In your code, char *lines[3];
defines an array of char
pointers. The pointers themselves do not point to any valid memory automatically. Unless initialized properly, attempt to use (or de-reference) them would lead to undefined behavior.
There are two common approach of achieving what you want (based on your requirement):
- Allocate a size at compile time and length-limit your input [i.e., pass the size of the buffer as a function argument, like
fgets()
] - Allocate memory at run time (allocator functions,
malloc()
and family) and resize based on the input length.
add a comment |
In addition to supplying a char*
which points to valid memory (as well suggested by others), getline2()
has other weaknesses to address.
Unknown size
getline2()
does not know how many characters can be saved. Suggest accepting a size parameter and adjust code to prevent overfilling s
.
// void getline2(char *s)
void getline2(char *s, size_t sz)
Infinite loop on EOF
When stdin
is closed or a rare input error occurs, getchar()
can perpetual return EOF
and never exit the loop.
257 values do not fit in char
int fgetc()
returns values in the range of unsigned char
and EOF
. Use int c;
and test loop for c != 'n' && c != EOF
// char c;
// while((c=getchar())!='n')
int c;
while((c=getchar())!='n' && c != EOF)
add a comment |
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%2f54002322%2fprogram-crashed-after-one-line-input-how-to-fix%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
In your code, char *lines[3];
defines an array of char
pointers. The pointers themselves do not point to any valid memory automatically. Unless initialized properly, attempt to use (or de-reference) them would lead to undefined behavior.
There are two common approach of achieving what you want (based on your requirement):
- Allocate a size at compile time and length-limit your input [i.e., pass the size of the buffer as a function argument, like
fgets()
] - Allocate memory at run time (allocator functions,
malloc()
and family) and resize based on the input length.
add a comment |
In your code, char *lines[3];
defines an array of char
pointers. The pointers themselves do not point to any valid memory automatically. Unless initialized properly, attempt to use (or de-reference) them would lead to undefined behavior.
There are two common approach of achieving what you want (based on your requirement):
- Allocate a size at compile time and length-limit your input [i.e., pass the size of the buffer as a function argument, like
fgets()
] - Allocate memory at run time (allocator functions,
malloc()
and family) and resize based on the input length.
add a comment |
In your code, char *lines[3];
defines an array of char
pointers. The pointers themselves do not point to any valid memory automatically. Unless initialized properly, attempt to use (or de-reference) them would lead to undefined behavior.
There are two common approach of achieving what you want (based on your requirement):
- Allocate a size at compile time and length-limit your input [i.e., pass the size of the buffer as a function argument, like
fgets()
] - Allocate memory at run time (allocator functions,
malloc()
and family) and resize based on the input length.
In your code, char *lines[3];
defines an array of char
pointers. The pointers themselves do not point to any valid memory automatically. Unless initialized properly, attempt to use (or de-reference) them would lead to undefined behavior.
There are two common approach of achieving what you want (based on your requirement):
- Allocate a size at compile time and length-limit your input [i.e., pass the size of the buffer as a function argument, like
fgets()
] - Allocate memory at run time (allocator functions,
malloc()
and family) and resize based on the input length.
edited Jan 2 at 7:02
answered Jan 2 at 6:51


Sourav GhoshSourav Ghosh
111k15131190
111k15131190
add a comment |
add a comment |
In addition to supplying a char*
which points to valid memory (as well suggested by others), getline2()
has other weaknesses to address.
Unknown size
getline2()
does not know how many characters can be saved. Suggest accepting a size parameter and adjust code to prevent overfilling s
.
// void getline2(char *s)
void getline2(char *s, size_t sz)
Infinite loop on EOF
When stdin
is closed or a rare input error occurs, getchar()
can perpetual return EOF
and never exit the loop.
257 values do not fit in char
int fgetc()
returns values in the range of unsigned char
and EOF
. Use int c;
and test loop for c != 'n' && c != EOF
// char c;
// while((c=getchar())!='n')
int c;
while((c=getchar())!='n' && c != EOF)
add a comment |
In addition to supplying a char*
which points to valid memory (as well suggested by others), getline2()
has other weaknesses to address.
Unknown size
getline2()
does not know how many characters can be saved. Suggest accepting a size parameter and adjust code to prevent overfilling s
.
// void getline2(char *s)
void getline2(char *s, size_t sz)
Infinite loop on EOF
When stdin
is closed or a rare input error occurs, getchar()
can perpetual return EOF
and never exit the loop.
257 values do not fit in char
int fgetc()
returns values in the range of unsigned char
and EOF
. Use int c;
and test loop for c != 'n' && c != EOF
// char c;
// while((c=getchar())!='n')
int c;
while((c=getchar())!='n' && c != EOF)
add a comment |
In addition to supplying a char*
which points to valid memory (as well suggested by others), getline2()
has other weaknesses to address.
Unknown size
getline2()
does not know how many characters can be saved. Suggest accepting a size parameter and adjust code to prevent overfilling s
.
// void getline2(char *s)
void getline2(char *s, size_t sz)
Infinite loop on EOF
When stdin
is closed or a rare input error occurs, getchar()
can perpetual return EOF
and never exit the loop.
257 values do not fit in char
int fgetc()
returns values in the range of unsigned char
and EOF
. Use int c;
and test loop for c != 'n' && c != EOF
// char c;
// while((c=getchar())!='n')
int c;
while((c=getchar())!='n' && c != EOF)
In addition to supplying a char*
which points to valid memory (as well suggested by others), getline2()
has other weaknesses to address.
Unknown size
getline2()
does not know how many characters can be saved. Suggest accepting a size parameter and adjust code to prevent overfilling s
.
// void getline2(char *s)
void getline2(char *s, size_t sz)
Infinite loop on EOF
When stdin
is closed or a rare input error occurs, getchar()
can perpetual return EOF
and never exit the loop.
257 values do not fit in char
int fgetc()
returns values in the range of unsigned char
and EOF
. Use int c;
and test loop for c != 'n' && c != EOF
// char c;
// while((c=getchar())!='n')
int c;
while((c=getchar())!='n' && c != EOF)
answered Jan 2 at 7:34


chuxchux
84.3k874154
84.3k874154
add a comment |
add a comment |
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%2f54002322%2fprogram-crashed-after-one-line-input-how-to-fix%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
5
You have declared an array of pointers but have not allocated memory for the pointers. Your code has undefined behavior because of that.
– R Sahu
Jan 2 at 6:50
1
Curious: who or what text suggested putting a
"n"
at the start of"n%s"
?– chux
Jan 2 at 6:52
1
Read How to debug small programs. You really should be able to find such bugs by yourself.
– Basile Starynkevitch
Jan 2 at 7:03
1
If the
printf
loop is not relevant, then it should be removed from the Minimal, Complete, and Verifiable example.– Werner Henze
Jan 2 at 7:07
1
@chux I disagree. It crashes prior to printf already. The while loop in
main
is probably noise too.getline2(lines[0])
would have sufficed to produce the crash.– Antti Haapala
Jan 2 at 8:30