|
Anyone can tell me How to remove segmentation fault from these program
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
char *buf;
int nread;
nread=read(0,&buf,strlen(buf)); // in these statement i am getting segmentation fault
printf("buffer size is %d\n",nread);
if(nread == -1)
{
write(2,"An error occured in read function\n",27);
}
else
{
if(nread==0)
write(2,"Data is not written to the filedescriptor\n",27);
else
write(2,"Everything went smoothly it has read the bytes\n",27);
}
}
output
sandeep@sandeep $ ./a.out <x
buffer size is 62
Everything went smoothly itSegmentation fault
|
|
|
|
|
Try:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
char buf[128];
int nread;
nread = read(0, buf, sizeof(buf));
printf("buffer size is %d\n", nread);
...
}
|
|
|
|
|
firstly thanks
the above will work, but why not the code what i wrote,whats wrong with my code
|
|
|
|
|
sandeep_dhruwa wrote: the above will work, but why not the code what i wrote,whats wrong with my code
Are you unable to see the difference between char *buf and char buf[128] ?
"Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
|
|
|
|
|
You should allocate memory for you buffer and call correctly the function.
For instance:
char buf[0x100];
int nread;
nread = _read( stdin, buf, sizeof(buf));
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
thanks
the above may work with memset()
thank you
|
|
|
|
|
You don't need memset , you must allocate memory for the buffer (you didn't), either onto the stack (as I did) or in the heap via, for instance, malloc .
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
Your buf variable is an uninitialized pointer, it will surely segfault when you pass it to strlen. I also suspect that read won't work the way you think it will work, but that's just a guess right now...
> The problem with computers is that they do what you tell them to do and not what you want them to do. <
> Life: great graphics, but the gameplay sux. <
|
|
|
|