C: Proper syntax for allocating memory using pointers to pointers.

Posted by ~kero-05h on Stack Overflow See other posts from Stack Overflow or by ~kero-05h
Published on 2010-06-06T04:57:37Z Indexed on 2010/06/06 5:02 UTC
Read the original article Hit count: 291

Filed under:

This is my first time posting here, hopefully I will not make a fool of myself.

I am trying to use a function to allocate memory to a pointer, copy text to the buffer, and then change a character. I keep getting a segfault and have tried looking up the answer, my syntax is probably wrong, I could use some enlightenment.

/* My objective is to pass a buffer to my Copy function, allocate room, and copy text to it.  Then I want to modify the text and print it.*/

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

int Copy(char **Buffer, char *Text);

int main()
{
 char *Text = malloc(sizeof(char) * 100);
 char *Buffer;

 strncpy(Text, "1234567890\n", 100);

 Copy(&Buffer, Text);
}

int Copy(char **Buffer, char *Text)
{
 int count;

 count = strlen(Text)+1;

 *Buffer = malloc(sizeof(char) * count);

 strncpy(*Buffer, Text, 5);

 *Buffer[2] = 'A'; /* This results in a segfault.  "*Buffer[1] = 'A';" results in no differece in the output. */

 printf("%s\n", *Buffer);

}

© Stack Overflow or respective owner

Related posts about c