爲了給出一些上下文,我爲我的計算機網絡類指定了一個讀取輸入文件並打包內容的任務。所以我有函數來初始化指向與每個圖層相關的數據的指針。 我沒有任何與作業的設計有關的問題,而是我正在處理的一個極其模糊的錯誤...C:struct-> char *:內容改變了:有人可以解釋這個嗎?
我已經包含了相關的結構定義和導致該錯誤的代碼行。 。由//******************
所包含的區域是錯誤發生的地方。第一個printf
的輸出與第二個printf
的輸出有所不同,儘管引用了同一個指針......我甚至沒有碰到指針,所以我很難弄清楚爲什麼內容全部壞突然...
我也包括了printf
輸出...
typedef struct
{
char *data;
int size;
} layer4_t;
typedef struct
{
char *data;
int nframes;
int overflow;
int size;
} layer3_t;
layer4_t *layer4_initForTransmit(const char *str)
{
//
// output variable initialization
//
layer4_t *y = malloc(sizeof(layer4_t));
if (!y) fprintf(stderr, "transmit: layer4: error: malloc failed\n");
// compute size of the data buffer (+1 for null byte)
y->size = strlen(str);
// memory allocation of (layer4)y.data
y->data = malloc(sizeof(y->size+1)); // ******** INCRIMINATING...
// copy contents of str to buf and copy over null byte
y->data[0] = '\0';
strcat(y->data, str);
if (DEBUG) printLayerData(y, 4);
return y;
}
layer3_t *layer3_initForTransmit(layer4_t *x)
{
//
// variable declarations
//
// 2. output variable
layer3_t *y;
// dummy ptrs
char *ptr; // 6
char *buf_ptr; // 1
// 7. i: frame index,
// 3. n_frames: number of frames,
// 5. tx_size: size of transmission buffer,
// 1. buf_size: size of the layer4 data;
// 8. offset: used to offset the buf_ptr
int i, n_frames, tx_size, buf_size, offset = 0;
//
// variable assignments
//
// 1. assign dummy pointers
buf_ptr = x->data;
buf_size = x->size;
// **********************
printf("%s\n", x->data);
// 2. allocate space for output variable
y = malloc(sizeof(layer3_t));
// 3. calculate number of frames
y->nframes = n_frames = buf_size/MSS;
// 4. overflow = sizeof(layer4.data) mod MSS + layer3 header size
y->overflow = buf_size % MSS + LAYER_3_HEAD_SIZE;
// 5. calculate size of tx (transmission) buffer
y->size = tx_size = LAYER_3_FRAME_SIZE * n_frames + y->overflow;
// 6. allocate and confirm space for tx buffer
y->data = ptr = malloc(tx_size+1); // +1 for null byte
if (!ptr) fprintf(stderr, "transmit: layer3: error: malloc failed\n");
printf("%s\n", x->data);
// **********************
...
output:
// first printf
this is a string of characters in the file sendfile.txt. willy wonka is a
fictional character in roald dahl's novel Charlie and the Chocolate Factory.
Willy Wonka is a manufacturer of premier brand chocolates and is planning to
retire soon. In anticipation of this, he begins a competition to find his
successor of the chocolate factory.
the way willy wonka intended on finding his successor was by throwing a contest
for 5 people to find a golden ticket inside one of his chocolate products.
?
// second printf
this is a string?/`3?
它必須覆蓋某個地方,這可能發生在調用此函數之前。你評論的部分看起來很溫和。在你將任何東西讀入'data'之前,你爲它分配了多少空間?如果這還不夠,那麼隨後的分配和寫入可能會通過'x-> data'訪問正在使用的內存塊(不正確)。也許你可以顯示那部分代碼。 – lurker
我同意'mbratch':你的'x-> data'必須在堆棧上,並被本函數中的局部變量覆蓋。 – TonyWilk
'y-> data = ptr = malloc(tx_size + 1); // +1空字節'x-data被分配,但從未填充任何有用的東西。 – wildplasser