需要 C 编程帮助:指针和 malloc
C programming help needed : pointers and malloc
输出应该是“钱包属于沃伦巴菲特,余额为 85500000000” 但我得到 “钱包属于沃伦巴菲特,余额为0.000000。你能告诉我我哪里出错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *owner;
long double balance;
} Wallet;
int main(int argc, char **argv) {
const char *owner = "Warren Buffett";
Wallet *wallet = (Wallet *) malloc(sizeof(Wallet));
wallet->owner = (char *) malloc(strlen(owner) * sizeof(char));
strcpy(wallet->owner, "Warren Buffett");
wallet->balance = 85500000000;
printf("The wallet belongs to %s with balance of %Lf",
wallet->owner, wallet->balance);
return 0;
}
您没有为 wallet->owner
分配足够的 space。
C 中的字符串由一系列字符和后跟一个终止空字节组成。您正在为 wallet->owner
分配 strlen(owner) * sizeof(char)
字节,这对于字符串中的字符来说足够了,但对于终止空字节来说就足够了。结果,您正在写入已分配内存的末尾。这会触发 undefined behavior,它可以表现为意外输出。
分配的加1 space:
wallet->owner = malloc(strlen(owner) + 1);
此外,sizeof(char)
保证为 1,因此可以省略与它的乘积,并且 you shouldn't cast the return value of malloc
.
输出应该是“钱包属于沃伦巴菲特,余额为 85500000000” 但我得到 “钱包属于沃伦巴菲特,余额为0.000000。你能告诉我我哪里出错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *owner;
long double balance;
} Wallet;
int main(int argc, char **argv) {
const char *owner = "Warren Buffett";
Wallet *wallet = (Wallet *) malloc(sizeof(Wallet));
wallet->owner = (char *) malloc(strlen(owner) * sizeof(char));
strcpy(wallet->owner, "Warren Buffett");
wallet->balance = 85500000000;
printf("The wallet belongs to %s with balance of %Lf",
wallet->owner, wallet->balance);
return 0;
}
您没有为 wallet->owner
分配足够的 space。
C 中的字符串由一系列字符和后跟一个终止空字节组成。您正在为 wallet->owner
分配 strlen(owner) * sizeof(char)
字节,这对于字符串中的字符来说足够了,但对于终止空字节来说就足够了。结果,您正在写入已分配内存的末尾。这会触发 undefined behavior,它可以表现为意外输出。
分配的加1 space:
wallet->owner = malloc(strlen(owner) + 1);
此外,sizeof(char)
保证为 1,因此可以省略与它的乘积,并且 you shouldn't cast the return value of malloc
.