相关疑难解决方法(0)

我是否施放了malloc的结果?

这个问题,有人建议意见,我应该不会投的结果malloc,即

int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

而不是:

int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

c malloc casting

2318
推荐指数
27
解决办法
22万
查看次数

为什么C++需要为malloc()进行强制转换,但C不需要?

我一直对此感到好奇 - 为什么在C++中我必须从mallocC而不是在C中转换返回值?

以下是C++中的示例:

int *int_ptr = (int *)malloc(sizeof(int*));
Run Code Online (Sandbox Code Playgroud)

以下是C++中不起作用的示例(无转换):

int *int_ptr = malloc(sizeof(int*));
Run Code Online (Sandbox Code Playgroud)

我听说在C中,事实上,输出输出malloc()是一个错误.

任何人都可以评论这个话题吗?

c c++ malloc

39
推荐指数
3
解决办法
8240
查看次数

直接写入std :: string的char*buffer

所以我有一个std::string并且有一个函数可以接受char*并写入它.既然std::string::c_str()std::string::data()回来了const char*,我不能用它们.所以我分配了一个临时缓冲区,用它调用一个函数并将其复制到std::string.

现在我计划处理大量信息,复制这个缓冲区会产生明显的影响,我想避免它.

有人建议使用&str.front()&str[0]但是它会调用未定义的行为吗?

c++ string language-lawyer c++14 c++17

7
推荐指数
1
解决办法
4664
查看次数

使用strcpy时打印垃圾

我有一个函数可以解析一些数据.我的问题是在使用strncpy后,当我尝试打印它时会得到一些垃圾.我尝试使用malloc使char数组具有确切的大小.

码:

void parse_data(char *unparsed_data)
{
char *temp_str;
char *pos;
char *pos2;
char *key;
char *data;
const char newline = '\n';

int timestamp = 0;

temp_str = (char*)malloc(strlen(unparsed_data));

g_print("\nThe original string is: \n%s\n",unparsed_data);


//Ignore the first two lines
pos = strchr(unparsed_data, newline);
strcpy(temp_str, pos+1);
pos = strchr(temp_str, newline);
strcpy(temp_str, pos+1);

//Split the line in two; The key name and the value
pos = strchr(temp_str, ':'); // ':' divides the name from the value
pos2 = strchr(temp_str, '\n'); //end of the …
Run Code Online (Sandbox Code Playgroud)

c malloc parsing text strncpy

2
推荐指数
1
解决办法
4327
查看次数

标签 统计

c ×3

malloc ×3

c++ ×2

c++14 ×1

c++17 ×1

casting ×1

language-lawyer ×1

parsing ×1

string ×1

strncpy ×1

text ×1