第一次在这里发帖,希望不要出洋相。
我正在尝试使用函数为指针分配内存,将文本复制到缓冲区,然后更改字符。我一直遇到段错误并尝试查找答案,我的语法可能有误,我可以使用一些启发。
/* 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);
}
最佳答案
您的问题只是优先级之一。 []
运算符的优先级高于一元-*
,因此该行被解析为:
*(Buffer[2]) = 'A';
...这不是您想要的。您实际上希望 *
先发生,所以您需要使用括号:
(*Buffer)[2] = 'A';
此外,您的 strncpy()
调用是错误的。如果复制的字符数等于长度,strncpy()
不会终止结果;由于您的内存直接来自 malloc()
,因此那里可能已经没有空终止符。在您遇到的 99.99% 的情况下,strncpy()
实际上是错误的工具 - 在此站点上搜索许多其他答案来解释原因。
可以改为调用 strncat()
:
(*Buffer)[0] = '\0'; /* Truncate to an empty string */
strncat(*Buffer, Text, 5);
关于C:使用指向指针的指针分配内存的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983149/