我没有得到以下字符串输出:
struct stringItem {
int len;
char str[1];
}
void allocationStringBuffer (char* stringContent, struct stringItem *string) {
// dynamically sized object
int n;
n = strlen(stringContent);
//struct stringItem *string = malloc(sizeof(struct stringItem) + n);
string = malloc(sizeof(struct stringItem) + n);
if (string == NULL) { // check if malloc is successful
printf("Memory allocation for string fails.\n");
// exit(-1);
}
strcpy(string->str, stringContent);
printf("Struct string: %s\n", string->str);
string->len = n;
}
in main:
struct stringItem *string2;
allocationStringBuffer ("helloWorld", string2);
printf("Struct string: %s\n", (*string2).str);
free(string2);
allocationStringBuffer ("another Statement...", string2);
printf("Struct string: %s\n", string2->str);
free(string2);
The result is:
Struct string: helloWorld
Struct string: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
Struct string: another Statement...
Struct string: ÉÉÉÉÉï Uï∞â∞¶SVWh♦☺
Thank you for your help.
[Updates with Thanks to ALL]
Here is the full working code. It has been resolved. Thank you to ALL.
struct stringItem {
int len;
char str[1];
};
void allocationStringBuffer (char* stringContent, struct stringItem** pstring) {
// dynamically sized object
int n;
n = strlen(stringContent);
struct stringItem *string;
string = malloc(sizeof(struct stringItem) + (n+1));
if (string == NULL) { // check if malloc is successful
printf("Memory allocation for string fails.\n");
// exit(-1);
}
strcpy(string->str, stringContent);
printf("Struct string: %s\n", string->str);
string->len = n;
*pstring = string; // Copy allocated pointer to out-parameter.
}
in main
struct stringItem *string2;
allocationStringBuffer ("helloWorld", &string2);
printf("Struct string: %s\n", (*string2).str);
free(string2);
allocationStringBuffer ("another Statement...", &string2);
printf("Struct string: %s\n", string2->str);
free(string2);
4 回答
在我看来,你需要做出这些改变:
这个似乎不对:
你想在这做什么?
string
是struct stringItem
的元素 . 所以我认为你只需要分配string = malloc(sizeof(struct stringItem));
p / s:如果你发布struct stringItem的声明,我应该很好
您缺少 malloc 调用中的终止空字符 .
strlen 为您提供不包括终止空字符的大小 .
问候,
你将一个指向stringItem的指针传递给函数,然后用
malloc
返回覆盖参数,然后丢弃它,从而泄漏它的内存 . 您有两种方法可以解决此问题:要么:
基本上,你必须以某种方式返回你的指针_551162 . 你无法向它发送一个指向堆栈上的
stringItem
的指针(即一个局部变量),就像你正在做的那样 .