使用memcpy的分段错误(C)
我在运行以下代码时遇到了“分段错误”错误,但我想知道为什么:使用memcpy的分段错误(C),c,memcpy,C,Memcpy,我在运行以下代码时遇到了“分段错误”错误,但我想知道为什么: int main() { char *str = "abcdefghijklmn"; void *str_v; memcpy(str_v, str, 14); printf("str_v is %s \n", (char *) str_v); return 0; } 谢谢您的帮助。因为您尚未为stru v分配任何内存,您需要首先为stru v分配内存: void *str_v = malloc(14); 将stru v定义为v
int main()
{
char *str = "abcdefghijklmn";
void *str_v;
memcpy(str_v, str, 14);
printf("str_v is %s \n", (char *) str_v);
return 0;
}
谢谢您的帮助。因为您尚未为
stru v
分配任何内存,您需要首先为stru v
分配内存:
void *str_v = malloc(14);
将stru v
定义为void*
类型,即它可以将指针存储为任何类型的变量。但是,要通过memcpy
将字符从源复制到目标,需要内存空间。因此,您需要使用malloc
-
char *str_v = malloc(strlen(str) + 1);
strlen
不计算str
指向的字符串中的终止空字节。因此,您必须为终止的空字节分配一个额外的字节
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// a string literal is read-only so make str
// const so attempting to change will cause
// compiler error
const char *str = "abcdefghijklmn";
// allocate memory dynamically to the
// string pointed to by str. +1 is for the
// terminating null byte since strlen does
// not count the null byte
char *str_v = malloc(strlen(str) + 1);
// malloc can fail if there is not enough
// memory to allocate. handle it
if(str_v == NULL) {
printf("error in memory allocation\n");
return 1;
}
// copy all bytes in the string pointed to
// by str to the buffer pointed to str_v.
// number of bytes to be copied is strlen(str) + 1
// +1 for copying the terminating byte as well
memcpy(str_v, str, strlen(str) + 1);
// print the copied string. It need not be
// cast to (char *) since str_v is already
// of type (char *)
printf("str_v is %s \n", str_v);
// free the dynamically allocated space
free(str_v);
return 0;
}
#包括
#包括
#包括
内部主(空){
//字符串文本是只读的,因此make str
//常量,因此尝试更改将导致
//编译错误
const char*str=“abcdefghijklmn”;
//将内存动态分配给
//str.+1指向的字符串用于
//终止空字节,因为strlen没有
//不计算空字节
char*str_v=malloc(strlen(str)+1);
//如果不够,malloc可能会失败
//要分配的内存。处理它
如果(str_v==NULL){
printf(“内存分配错误”);
返回1;
}
//复制指向的字符串中的所有字节
//通过str指向str_v的缓冲区。
//要复制的字节数为strlen(str)+1
//+1用于复制终止字节
memcpy(str_v,str,strlen(str)+1);
//打印复制的字符串。它不需要
//强制转换为(char*),因为str_v已经
//类型(字符*)
printf(“str_v是%s\n”,str_v);
//释放动态分配的空间
免费(str_v);
返回0;
}
您正在memcpy(str_v,str,14)中使用未初始化指针代码>,若要修复它,可以在其前面添加以下语句:
str_v = malloc(14);
if (str_v == NULL) { /* malloc failed */ }
你可以这么做
char * str_v = strdup( str );
发件人:
#包括
字符*strdup(常量字符*s);
函数的作用是:返回指向新字符串的指针
这是字符串s的副本。
使用malloc(3)获得新字符串的内存,
并且可以用free(3)释放。
声明指针void*stru v
不会自动指向某个地方。
char * str_v = strdup( str );
#include <string.h>
char *strdup(const char *s);
The strdup() function returns a pointer to a new string
which is a duplicate of the string s.
Memory for the new string is obtained with malloc(3),
and can be freed with free(3).