Why the following code is giving me an error like this

make: *** [all] Segmentation fault (core dumped)

the source code is like this

#include <stdio.h>

int main()
{
    int i;
    char* ptr = NULL;
    *(ptr + 0) = 'H';
    *(ptr + 1) = 'e';
    *(ptr + 2) = 'l';
    *(ptr + 3) = 'l';
    *(ptr + 4) = 'l';
    *(ptr + 5) = 'o';

    for (i = 0; i < 6; i++)
    {
    printf("%c", *(ptr + i));
    }
    return 0;
}

But this runs okay

printf("%c", *(ptr + 0));
printf("%c", *(ptr + 1));
printf("%c", *(ptr + 2));
printf("%c", *(ptr + 3));
printf("%c", *(ptr + 4));
printf("%c", *(ptr + 5));

Edited 1 Year Ago by Mayukh_1

Your pointer is null. Any attempt to dereference it invokes undefined behavior. The second snippet running okay is merely bad luck because it suggests that the code isn't glaringly broken.

hey thanks for the reply..But even if I am not assigning the pointer with NULL, it is still giving me this output with an warning that ptr might be uninitialized..

And I still don't understand that why the second snippet is still working..Can you please elaborate..??

You need to initialize the pointer to somewhere real, somewhere you actually own:

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

int main()
{
    char* ptr = malloc(6);
    int i;

    *(ptr + 0) = 'H';
    *(ptr + 1) = 'e';
    *(ptr + 2) = 'l';
    *(ptr + 3) = 'l';
    *(ptr + 4) = 'l';
    *(ptr + 5) = 'o';

    for (i = 0; i < 6; i++)
    {
        printf("%c", *(ptr + i));
    }

    free(ptr);

    return 0;
}

If you don't point it anywhere, it points to some random place in memory which begs for a segmentation fault. If you do point it to NULL, it's null, and by definition not a real location...

And I still don't understand that why the second snippet is still working..Can you please elaborate..??

Why it works is irrelevant. Figuring out some quirk of memory mapping on the exact configuration of code, compiler, OS, hardware, and such would be a waste of effort as if anything changes the result could as well. It could also stop working at any time.

Hey thanks again for a reply..Actually I need to discuss the real probelm now..

I am basically implementing the substr of C++ in C..
My oblective is not to use any methods in string library, not to use any dynamic memory allocation & not use any global variable..And my code looks like this..

str.h

#ifndef _str_h_
#define _str_h_

struct STRSTR
{
    char* MainStr;
    char* SubStr;
};

char* str_str(int, int, struct STRSTR* sample);
void init(char*, struct STRSTR* sample);
// char temp[100];

#endif /* _str_h_ */

str.c

#include "str.h"
#include <stdio.h>
void init(char* str, struct STRSTR* sample){
    sample->MainStr = str;
}


char* str_str(int index, int size, struct STRSTR* sample){
    int length = 0;
    while ( *(sample->MainStr + length)!= '\0' )
        length++;
    char temp[length];
    if (index > length)
        printf( "ERROR!! Index value is greater than the actual size" );
    else{
        int i;
        for ( i = index; i < size; i++ ) {
            temp[i] = *(sample->MainStr + i);
        }   
        temp[size] = '\0';
        sample->SubStr = temp;

    }

return sample->SubStr;
}

and main.c

#include "str.h"
#include <stdio.h>
int main() {

    struct STRSTR sample;
    init((char*)"Hello World", &sample);
    char* out = str_str(0, 5, &sample);
    printf("%s", out);


return 0;
}

Now this code is not putting up the right value in SubStr and I think I know the reason..I am pointing the SubStr pointer to the temp variable whose scope limits it only within the str_str function & hence we the program leaves the function the local array is getting destroyed and hence I get no answer when I try to derefernce the SubStr pointer...

Now this code works perfect when I declare the temp as global in str.h..

Can you tell how to implement it without using global variable (I always try to avoid sharing variables), sting library, and dynamic memory allocation..

I know the reason

And you're correct.

Can you tell how to implement it without using global variable (I always try to avoid sharing variables), sting library, and dynamic memory allocation..

You only have one option with those restrictions, and the only option is to have the caller provide a buffer. Something like this, I suppose:

#include <stdio.h>

char *substr(const char *src, size_t index, size_t size, char *buffer, size_t n)
{
    int length = 0;

    while (src[length] != '\0')
    {
        length++;
    }

    if (index > length)
    {
        return NULL;
    }
    else
    {
        int i, k = 0;

        for (i = index; src[i] != '\0' && k < size && k < n - 1; i++)
        {
            buffer[k++] = src[i];
        }

        buffer[k] = '\0';
    }

    return buffer;
}

int main(void)
{
    char buf[BUFSIZ];

    printf("'%s'\n", substr("Hello World", 0, 5, buf, sizeof buf));
    printf("'%s'\n", substr("Hello World", 6, 5, buf, sizeof buf));

    return 0;
}
This article has been dead for over six months. Start a new discussion instead.