-3

I declared a character pointer and allocated memory dynamically and initialized it with a string now i want to add character to the pointer. I tried the following code but it is giving segmentation fault(core dumped) error.

#include <stdio.h>

int main()
{
    char *ch;
    ch = (char *)malloc(sizeof(char)*32);
    ch = "hello";
    ch[5] = 'k';
    ch[6] = '\0';
    printf("%s", ch);
    return 0;
}
Gara Ranjeet
  • 13
  • 1
  • 3
  • 2
    `ch = "hello"` overwrites the pointer and thus throws away the `malloc` memory. Furthermore, it points it to a string literal which cannot be written to. Use `strcpy` instead. – kaylum Dec 18 '20 at 10:18
  • Please don't cast the return value of `malloc`. See [here](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) for more details. – costaparas Dec 18 '20 at 10:19

1 Answers1

0

Yes you have allocated 32 chars for ch pointer. But right on the next line you're reassigning another statically allocated string to it which overrides the pointer to the dynamic memory that was stored in ch.

  ch = (char *)malloc(sizeof(char)*32);
  ch = "hello";

The result of this is, you lose the handle to the dynamic memory and now you have no way of freeing that memory with free(). If you want to assign "hello" to ch, you can do it with the strcpy function define in <string.h>.

#include <stdio.h>
#include <string.h>
int main()
{
    char *ch;
    ch = (char *)malloc(sizeof(char)*32);
   // ch = "hello";
    strcpy(ch, "hello");
    ch[5] = 'k';
    ch[6] = '\0';
    printf("%s", ch);
    free(ch);
    return 0;
}

Strcpy just iterates through the array and assigns every character one by one. Also never forget to free the dynamic memory allocated.

Vahan
  • 166
  • 13