gpt4 book ai didi

Char* 在函数中使用 malloc 创建,编译器说地址在堆栈上,无法返回

转载 作者:行者123 更新时间:2023-12-04 11:16:25 25 4
gpt4 key购买 nike

我正在编写一个函数,该函数应该将字符串作为输入并在单词周围添加引号,然后返回指向新修改后的字符串的指针。

//add quotes around a single word
char** _add_quotes(char* word){
int char_count = 0;
while(word[char_count] != '\0'){
char_count++;
}
char* word_quotes = malloc((char_count+3) * sizeof(*word_quotes));
word_quotes[0] = '\"';
for(int i =0; i < char_count; i++){
word_quotes[i+1] = word[i];
}
word_quotes[char_count+1] = '\"';
word_quotes[char_count + 2] = '\0';
return (&word_quotes);
}

这是它返回的地方

char** new_word_w_qs = _add_quotes(new_word); //add quotes
//copy new word with quotes to the final string
for (int m = 0; m < word_len; m++){
new_string[string_index] = *new_word_w_qs[m];
string_index++;
}

我期望它返回堆上字符串的地址,但我得到了一个错误。警告:返回与局部变量“word_quotes”关联的堆栈内存地址 [-Wreturn-stack-address] 返回(&word_quotes); ^~~~~~~~~~~

最佳答案

char f() {
char a = 'a';
return &a;
}

函数返回后,变量a 不再存在。所以函数返回后,变量a不存在,变量&a的地址在函数返回后无效,函数返回后那里没有内存。

char **f2() {
char *b = "abc";
return &b;
}

这个是一样的。函数后b变量不存在,所以函数返回后b变量地址无效。不管它是不是指针。 b变量保存的地址仍然有效,但是函数返回后b变量的地址就失效了。

只是按值返回指针,而不是指向指针的指针。

//add quotes around a single word
char* _add_quotes(char* word){
...
char* word_quotes = malloc((char_count+3) * sizeof(*word_quotes));
...
// this is the value as returned by malloc()
// the pointer value returned by malloc still valid after the function returns
return word_quotes;
}

并且您的函数可以重写为使用标准库函数:

char* _add_quotes(char* word){
char* word_quotes = calloc((strlen(word) + 3), sizeof(*word_quotes));
if (word_quotes == NULL) return NULL;
strcat(word_quotes, "\"");
strcat(word_quotes, word);
strcat(word_quotes, "\"");
return word_quotes;
}

甚至:

char* _add_quotes(char* word){
char* word_quotes = calloc((strlen(word) + 3), sizeof(*word_quotes));
if (word_quotes == NULL) return NULL;
sprintf(word_quotes, "\"%s\"", word);
return word_quotes;
}

关于Char* 在函数中使用 malloc 创建,编译器说地址在堆栈上,无法返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com