c - 我这样做对吗? - C代码

标签 c memory dynamic allocation

当我运行它时,它说大小是 4,而实际上是 6。它在这里这样做:

printf("String Size: %u\n", sizeof some_string.basic_string);

我是 c 内存分配的新手,以前从未使用过 malloc。我使用的 malloc 对吗?

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

typedef struct String String;

struct String {
  char *basic_string;
};

String String_New(char basic_string[]) {
  String temp;
  temp.basic_string = (char *) malloc(sizeof basic_string);
  strcpy(temp.basic_string, basic_string);
  return temp;
}

void String_Delete(String *string) {
  free(string->basic_string);
  string->basic_string = NULL;
}

int String_GetSize(String string) {
  int i = 0, s = 0;
  while (string.basic_string[i] != '\0') {
    i++;
    s++;
  }
return s;
}

int main(int argc, char *argv[]) {
  String some_string = String_New("hello");
  printf("String Literal: %s\n", some_string.basic_string);
  printf("String Size: %u\n", sizeof some_string.basic_string);
  printf("String Length: %d\n", String_GetSize(some_string));
  String_Delete(&some_string);

  if (some_string.basic_string == NULL) {
    return 0;
  }

  return 1;
}

最佳答案

char *basic_string; 是指向一些内存的指针,指针的大小(在 32 位系统上)是 32 位 = 4 字节。 Sizeof 不知道您在此地址保留的内存大小。

通常没有办法获得 malloc 保留的内存大小——尽管您的系统可能有一些专用调试功能来执行此操作。

关于c - 我这样做对吗? - C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281370/

相关文章:

c - 在预定的裸机嵌入式应用程序中使用内部硬件看门狗的最安全方法是什么(以及为什么)?

arrays - MIPS:将用户输入字符串与内存中的字符串数组进行比较

java - 在 Java 中模拟动态作用域?

java - 使用用户输入创建新对象 [JAVA]

python - 从 C 调用 python 回调时如何修复 "SystemError: null argument to internal routine"错误

C - 如何在 while 循环中处理用户输入

memory - 如何使用页表将虚拟地址转换为物理地址?

memory - 查找 PBS 作业使用的最大内存

ios - 自动替换 UIView 中的 subview

python - 调用函数时如何在 ctyps 中返回数组