0

我明白这个程序没有分配足够的内存。

我需要帮助的是描述执行此代码时发生的情况的解释。

我输入“由于只分配了 4 个空间,因此没有提供足够的空间,因此会导致错误。” 这对我来说听起来不对。谢谢。

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

int main()
{ 
    char word1[20];
    char *word2;

    word2 = (char*)malloc(sizeof(char)*20);

    printf("Sizeof word 1: %d\n", sizeof (word1));  //This line outputs 20
    printf("Sizeof word 2: %d\n", sizeof (word2));  //This line outputs 4
                                                    //before & after I used malloc
    strcpy(word1, "string number 1");
    strcpy(word2, "string number 2"); <---- What is this doing

    printf("%s\n", word1);
    printf("%s\n", word2);
}
4

3 回答 3

4

word2 是一个未初始化的指针。向其写入数据会产生未定义的后果,但可能会崩溃。您需要在堆栈上(如 for word1)或动态地使用malloc.

char *word2 = malloc(20); // arbitrary value. could use strlen(some_str)+1 also
strcpy(word2, "string number 2"); // works now

或者,对于 posix 系统

char *word2 = strdup("string number 2");

无论哪种情况,请确保稍后调用free以将此内存返回给系统。

请注意,即使在分配内存之后,sizeof(word2)仍将保持 4。这是因为word2has 类型char*因此sizeof报告的大小char*而不是它指向的内存。

于 2013-02-12T16:23:12.493 回答
2

sizeof( word2 ) 返回 4 因为这是指针的大小

char *word2;

是一个指针,为它分配了 0 个字节(不是你提到的 4 个)

sizeof( word1 ) 返回 20 因为这是数组的大小

char word1[20]

是一个数组,为它保留了 20 个字节

于 2013-02-12T16:24:14.647 回答
0

在你的程序word2中会有一些以前的值或者可能是一个垃圾值。当您执行时strcpy(word2, "string number 2");,您正在尝试写入您无权访问的位置,因此您的程序崩溃。因此,您需要分配足够的内存供程序写入。

于 2013-02-12T16:28:14.613 回答