关于指针的奇怪之处

时间:2013-02-05 13:12:18

标签: c visual-studio pointers

我对VS C ++有一些误解。在2010版本中,下面的代码工作正常:我可以得到一个字符串,我可以释放后记。

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

 #define MAX 14

 void GetString(char **str);

 int main(int argc, char *argv[])
 {
    char *str = NULL;
    GetString(&str);
    printf("%s\n", str);

    getchar();

    free(str);

    return 0;
 }

 void GetString(char **str)
 {
    char *s = (char *) malloc(sizeof(char) * MAX);
    strcpy(s, "HELLO, WORLD!");
    *str = s;
 }

但在VS 2008中,上面的代码最终会出现内存损坏错误。我想,使用的标准存在细微差别。 我是对的吗?如果不是,请告诉我,为什么相同的代码在Visual Studio的不同版本中不起作用?

事先感谢您的回答。

P.S。我很想知道会发生什么,但还无法找到有关该主题的任何信息。

p.p.s。使用的语言 - C

1 个答案:

答案 0 :(得分:1)

您没有包含所需的标头,这意味着不同编译器可能会对您的代码进行不同的解释。你应该添加:

#include <stdlib.h>

使malloc()定义明确的功能。

您还在呼叫strcpy(),因此您需要:

#include <string.h>

并做I / O,您需要:

#include <stdio.h>

另外,在C中:

char *s = (char *) malloc(sizeof(char) * MAX);

最好写成:

char *s = malloc(MAX);

因为

  1. 这是a bad idea to cast the return value of malloc()
  2. sizeof (char)始终为1,因此只会增加混乱。
  3. 最后,您应该在使用返回的指针之前检查malloc()是否成功。

相关问题