根据这个问题:When should I use malloc in C and when don't I?
使用malloc分配内存应该允许我更改数组中的一个字符。但是,该程序在运行时崩溃。有人能告诉我吗?(同时,free(ptr)
会导致不同的崩溃,这就是为什么它会被注释掉)。
char* ptr;
ptr = (char *)malloc(sizeof(char[10]));
ptr = "hello";
ptr[0] = 'H';
printf("The string contains: %s\n", ptr);
//free (ptr);
return 0;
发布于 2014-06-08 20:45:57
您的程序崩溃,因为这行
ptr = "hello";
从前面的行完全取消malloc
的效果:
ptr = malloc(sizeof(char[10])); // No need to cast to char*
它还会在执行过程中造成内存泄漏,因为malloc
返回的地址在分配之后将无法恢复。
一旦完成赋值,设置ptr[0] = 'H'
的尝试就会导致崩溃,因为您试图修改字符串文本本身的内存--即未定义的行为。
在C语言中,如果以后要修改字符串,则需要复制字符串,而不是分配字符串。用strcpy
调用替换赋值,以解决此问题。
strcpy(ptr, "hello");
发布于 2014-06-08 20:47:18
有几件事需要解决:
char* ptr = 0;
ptr = (char *)malloc(sizeof(char)*10);
if(!ptr)
return 0; // or something to indicate "memory allocation error"
strcpy(ptr, "hello");
ptr[0] = 'H';
printf("The string contains: %s\n", ptr);
free (ptr);
return 0;
这将在main()中正确编译和运行。
https://stackoverflow.com/questions/24110640
复制相似问题