[英]bus error: 10. C code, malloc example
When I try compiling the following C code, i get a bus error. 当我尝试编译以下C代码时,出现总线错误。 I'm guessing it has something to do with the way I have called memcpy, however I cant figure it out.
我猜它与我称为memcpy的方式有关,但是我无法弄清楚。 Any help would be greatly appreciated!
任何帮助将不胜感激!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *p = (char*)malloc(sizeof(char)*11);
// Assign some value to p
p = "hello";
char *name = (char*)malloc(sizeof(char)*11);
// Assign some value to name
name = "Bye";
memcpy (p,name,sizeof(char)*10); // Problem begins here
return 0;
}
Here p
points to a string literal after your assignment, NOT to your allocated memory! 这里
p
指向分配后的字符串文字,而不是分配的内存!
Then you try to write into that memory with memcpy
. 然后,您尝试使用
memcpy
写入该内存。
Many C compilers allocate string literals in read-only memory, hence the bus error. 许多C编译器在只读内存中分配字符串文字,因此会产生总线错误。
To fix your problem, you should copy the characters h, e, l, l, and o into the space you allocated for p
in the first line of main
, using strncpy
. 要解决您的问题,您应该使用
strncpy
将字符h,e,l,l和o 复制到main
的第一行中为p
分配的空间中。 This keeps p
pointing to the memory you allocated yourself; 这使
p
指向您自己分配的内存; the later memcpy
will be fine (provided you don't overflow your buffer of course). 以后的
memcpy
就可以了(前提是您当然不会溢出缓冲区)。
Note that in general when you assign to a string variable directly you are making the variable point to a different memory address. 请注意,通常在直接分配给字符串变量时,会将变量指向另一个内存地址。 In your code you have allocated space for a couple of strings but when you assign string literals to the variables, you are changing the location to which they point, causing a memory leak.
在代码中,您已经为几个字符串分配了空间,但是当您为变量分配字符串文字时,您将更改它们指向的位置,从而导致内存泄漏。
In your code, that p = "hello"
the "hello"
return a pointer which point to a string hello
and the hello can't be change. 在您的代码中,
p = "hello"
和"hello"
返回一个指向字符串hello
的指针,并且hello不能更改。 You use p = "hello"
means make p
point to this string too. 您使用
p = "hello"
意味着使p
指向该字符串。 So when you try to change it, you will get an error. 因此,当您尝试更改它时,会出现错误。 The right way is like follows:
char a[] = "hello";
正确的方法如下:
char a[] = "hello";
or 要么
char *a = malloc(sizeof(char)*11); /*cast is not good*/
strcpy (a, "hello");
BTW, use malloc
had better NOT using cast like (char *)
or (int *)
. 顺便说一句,使用
malloc
最好不要使用(char *)
或(int *)
这样的(char *)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.