0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
        char compliance[256] = {'\0'};
        if(compliance == NULL)
        {
                printf("compliance is null \n");
                return 0;
        }
        printf("length of compliance %zd \n",strlen(compliance));
        return 0;
}

Output:

length of compliance 0


int main(int argc, char *argv[])
{
        char compliance[256] = {'\0'};
        memset(compliance,0,256);

        if(compliance == NULL)
        {
                printf("compliance is null \n");
                return 0;
        }
        printf("length of compliance %zd \n",strlen(compliance));
        return 0;
}

Output length of compliance 0

As many of you have pointed out I wanted to use memset (instead of memcpy).But still don't get why in the second program compliance is not NULL? or in other words How do I make it NULL?

1
  • 3
    I'm quite certain you want to use memset, not memcpy, just as i'm sure It is entirely unneeded given your initializer presence. Commented Nov 26, 2013 at 1:19

3 Answers 3

3

both programs are broken;

    if(compliance == NULL)

makes no sense as compliance is never NULL (it is a variable on stack)

In the second part

    memcpy(compliance,0,256);

copies from source address 0 (NULL) which causes segfault on most platform. You probably want to use memset here

Sign up to request clarification or add additional context in comments.

3 Comments

the first line will get optimized out and looks very much like a debugging statement to help remove that case from being the reason for the core dump - the second, ....
I didn't understand you first comment ? (compliance == NULL) why doesn't it make sense?
because compliance is an array and it is ensured that it is not at a NULL address. You might want char *compliance = malloc(256) or so.
2

compliance is an array, not a pointer (An array name are automatically converted to a pointer to the first element in some situations, but arrays are not pointers), it will never be equal to a null pointer.

The segmentation fault in the second example is caused by the call to memcpy.

memcpy(compliance,0,256);

You are copying from a null pointer. Probably what you want is memset.

Comments

1

you probably meant memset

you are copying from address 0 - 256 bytes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.