簡體   English   中英

在此代碼段中realloc有什么作用?

[英]What does realloc do in this code snippet?

我在這里瀏覽了C中的relloc示例。 我無法弄清楚此代碼段中的realloc()在做什么,因為即使我注釋掉realloc語句,程序也可以正常運行。 我將代碼再次附加到此處,以便更輕松地進行閱讀。

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

int main()
{
char *str;

/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s,  Address = %u\n", str, str);

/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s,  Address = %u\n", str, str);

free(str);

return(0);
}

據我了解,malloc()最初將字符串分配為15個字節長,然后realloc()將其重新分配為25個字符長。 但是,即使我從代碼段中刪除了realloc()語句,它仍如何正常工作? 我是否從中錯過了一些東西?

但是,即使我從代碼段中刪除了realloc()語句,它仍如何正常工作?

如果刪除realloc() ,則代碼可能工作正常,但這是偶然的。 代碼仍然是錯誤的,它有一個緩沖區溢出,結果是“未定義的行為”-這意味着它可能工作正常,可能崩潰,可能給出錯誤的答案,可能會格式化硬盤-可能做任何事情

修正您的代碼。

如果您使用的是GCC 4.8或更高版本,建議您使用地址清理器。 像這樣編譯您的代碼:

gcc main.c -o main -fsanitize=address -Wall -Wextra
                   ^^^^^^^^^^^^^^^^^^

這需要在系統上安裝地址清理程序庫。 或者,在Valgrind的memcheck工具中運行代碼。

valgrind ./main

兩種工具都將顯示您的程序錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM