why it is not work?

Y

yezi

Hi: all:

The code is like :

char *data;


data = malloc(1000);
if (data = NULL)
{
printf (" can not assign the memory for the packet\n");
exit(1);
}

memset(data,'\0',1000);


The code is failure say "Segmentation fault"
The problem is memset, why?


Thanks
 
Y

yezi

right, thanks. but one question is " if I do not write the memset(data,
'\0',1000);

The code runs fine. only append the sentence , then crash. why?
 
P

pemo

yezi said:
Hi: all:

The code is like :

char *data;


data = malloc(1000);
if (data = NULL)
{
printf (" can not assign the memory for the packet\n");
exit(1);
}

memset(data,'\0',1000);


The code is failure say "Segmentation fault"
The problem is memset, why?

Try

if(NULL = data)

hint:
= and ==
 
L

Lew Pitcher

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
right, thanks. but one question is " if I do not write the memset(data,
'\0',1000);

The code example was

) char *data;
)
) data = malloc(1000);
) if (data = NULL)
) {
) printf (" can not assign the memory for the packet\n");
) exit(1);
) }
)
) memset(data,'\0',1000);
The code runs fine. only append the sentence , then crash. why?


Because, you use memset() to set memory pointed to by pointer data
If pointer data is not initialized (or is initialized incorrectly), then
memset() writes over random memory. That invokes bad behaviour in your program
and it crashes.

So, why would data not be initialized correctly?
It wouldn't be initialized if, for some reason, malloc() failed to allocate
memory. If malloc() can't allocate memory, it returns NULL, and dereferencing
NULL can cause this problem.

Your code also has an error:
) if (data = NULL)
) {
)...
) }
Here, you don't /test/ the value of data against NULL, you /change/ the value
of data /to/ NULL. And since NULL evaluates false, the body of the if
statement doesn't get executed. So, you wipe out your pointer, replace it with
NULL, bypass your abort test, and promptly memset() NULL to some data.

Bang! Down you go.

If you /correct/ the test (don't remove it, /fix/ it), you will exit(1) (an
improper value, according to the standard, BTW) rather than memset() when data
== NULL


- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDl6qxagVFX4UWr64RAtqJAKCHubGWkha9uTGGx13mBRy7VNBNIQCfQ+Oa
qB+tBI9P+1olfyRmU8A1BO8=
=SeWK
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,933
Members
47,472
Latest member
blackwatermelon

Latest Threads

Top