开发者

C: Proper syntax for allocating memory using pointers to pointers

This is my first time 开发者_JAVA百科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);

}


Your problem is simply one of precedence. The [] operator has higher precendence that unary-*, so the line is parsed as if it was:

*(Buffer[2]) = 'A';

...which is not what you want. You actually want the * to happen first, so you need to use parantheses:

(*Buffer)[2] = 'A';

Additionally, your strncpy() call is wrong. strncpy() does not nul-terminate the result if the number of characters copied is equal to the length; and since your memory comes straight from malloc(), there may not be a nul-terminator there already. strncpy() is actually the wrong tool in 99.99% of the cases that you will encounter - search on this site for numerous other answers explaining why.

A call to strncat() can be used instead:

(*Buffer)[0] = '\0';    /* Truncate to an empty string */
strncat(*Buffer, Text, 5);


*Buffer[2] is getting interpreted as *(Buffer[2]). What you want is (*Buffer)[2].


The problem is that *Buffer[2] means *(Buffer[2]) - you're trying to dereference the wrong pointer. You want to use (*Buffer)[2].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜