For the getline() function, I tried two method to allocate memory space for string, but the first one works, the second doesn’t. Can anyone explain why the second won’t work?
The first one
#include <stdio.h>
int main()
{
int bytes_read;
int nbytes = 100;
char *my_string;
puts ("Please enter a line of text.");
/* These 2 lines are the heart of the program. */
my_string = (char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("You typed:");
puts (my_string);
}
return 0;
}
The second one:
#include <stdio.h>
int main()
{
int bytes_read;
int nbytes = 100;
char my_string[nbytes+1];
puts ("Please enter a line of text.");
/* These 2 lines are the heart of the program. */
bytes_read = getline (&my_string, &nbytes, stdin);
if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("You typed:");
puts (my_string);
}
return 0;
}
The second one can be compiled, but when I execute it:
bash-3.2$ ./a.out
Please enter a line of text.
lsdfa
Bus error: 10
It says Bus error: 10
I don’t know what is the possible reason, can anyone help me?
The signature for
getlinerequires a pointer to achar*so that it may be modified. This is becausegetlineis supposed to be allowed to callreallocon thechar*or allocate achar*if you pass achar*which points to 0:In the first case everything is fine as the pointer you’ve passed to
getlinecan be modified.In the second case you’re passing a pointer to a
chararray, which itself cannot be modified. As you’ve found, unfortunately&my_stringends up looking likechar**, so the compiler does not complain (but it may with-Wall).Basically, since
getlineneeds to be able to modify whatlineptrpoints to, in your second case this cannot be done (hence the bus error).