Segmentation error - char pointer

In the code below, the line:

*end = *front;

gives a segmentation error. I asked a similar question here , but I'm not sure if this is because I have two copies of num. Please explain why this is happening. Thanks.

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

char* getPalin(char* num);

int main()
{
    char* num = (char*)malloc(100);

    num = "123456";

    printf("%s\n", getPalin(num) );

    return 0;
}

char* getPalin(char* num)
{
    int length = strlen(num);

    if ( length % 2 == 0 )
    {
        char* front = num;
        char* end = num + strlen(num) - 1;  //pointer to end

        while( front != num + (length/2) )  //pointers not middle yet
        {
            *end = *front;

            printf("%c", *end);

            front++;
            end--;
        }
    }

    return num;
}
+5
source share
4 answers

These two lines:

char* num = (char*)malloc(100);
num = "123456";

have the following effect.

The first allocates 100 bytes and sets numto indicate these bytes.

The second num change points to the string "123456", which is almost certainly in read only memory.

. malloc 'd num, , :

strcpy (num, "123456");

, , :

num = "123456";
+15

strncpy(num, "123456", 100);

num = "123456";
+4

.

num malloc.

, :

char* num = "123456";

" ", , , .

strncpy, strcpy "123456", , null, n 100 ( ). , malloc, null (memset (num, 0, 100)), , .

, . strcpy_s strncpy_s, , .

+1

:

  char* num = (char*)malloc(100);

num .

 num = "123456";

In this line, you used num when you declared it as a string. This is a violation of segmentation and, therefore, segregation. Preferred (correct) syntax for your code:

   char num[100];
   strcpy(num,"123456"); //Even if you use num="123456"; here it would still be wrong

OR

  char* num = (char*)malloc(100);
  strcpy(num,"123456");

OR

  char num[100]={'1','2','3','4','5','6'};

Any of them will do your job.

0
source

All Articles