malloc + 4 ?? [英] malloc + 4??

查看:58
本文介绍了malloc + 4 ??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.yep-mm.com/res /soCrypt.c


我的程序中有2个malloc',当我把它们的内容写入

时屏幕或者到一个文件,还有4个字符。


据我所知,注册malloc和写入

信息的代码malloc是坚实的。为什么然后ismy程序返回

另外4个字符?


注册malloc 1:

第192行


注册malloc 2:

第214行

写入malloc 1:

第200行 - 205 < br $>
写给malloc 2:

221行 - 225

显示malloc 2:

line 157


写malloc 2:

第251行


这是'你执行的方式程序:


socrypt.exe / e:我输入.txt:o output.txt:一个keya.txt:B keyb.txt:k

keyout .txt


**请注意输入,keya和keyb文件必须存在,否则程序将会返回错误代码。


如果你在input.txt文件中写入一个文本字符串,它会将相同的

字符串写入output.txt文件中,另外加上4个字符。


1024 char随机''masterkey''也写到keyout.txt文件

wit另外4个字符。


为什么会这样?我完全不知所措,花了几天时间试图计算出来。

http://www.yep-mm.com/res/soCrypt.c

I have 2 malloc''s in my program, and when I write the contents of them to
the screen or to a file, there aren addition 4 characters.

As far as I can tell, both the code to register the malloc and to write
information into the malloc is solid. Why then ismy program returning an
additional 4 characters?

register malloc 1:
line 192

register malloc 2:
line 214

write to malloc 1:
line 200 - 205

write to malloc 2:
line 221 - 225

display malloc 2:
line 157

write malloc 2:
line 251

Here''s how you execute the program:

socrypt.exe /e :i input.txt :o output.txt :A keya.txt :B keyb.txt :k
keyout.txt

**note that the input, keya, and keyb files must exist or the program will
return an error code.

If you write a text string into the input.txt file, it will write the same
string into the output.txt file plus an addition 4 characters.

The 1024 char random ''masterkey'' is also written out to the keyout.txt file
with an addition 4 characters.

Why is this happening? I''m totally baffled and have spent days trying to
figure this out.

推荐答案

Kevin Torr< ke *******@hotmail.com>潦草地写道:
Kevin Torr <ke*******@hotmail.com> scribbled the following:
http:// www.yep-mm.com/res/soCrypt.c
我的程序中有2个malloc',当我把它们的内容写到
屏幕或者文件,还有4个字符。
据我所知,注册malloc和将信息写入malloc的代码都很可靠。那么为什么我的程序会返回另外4个字符?
http://www.yep-mm.com/res/soCrypt.c I have 2 malloc''s in my program, and when I write the contents of them to
the screen or to a file, there aren addition 4 characters. As far as I can tell, both the code to register the malloc and to write
information into the malloc is solid. Why then ismy program returning an
additional 4 characters?




C标准说允许malloc分配比
$ b $更多的内存请求。


-

/ - Joona Palaste(pa*****@cc.helsinki.fi)------ -------芬兰-------- \

\-- http://www.helsinki.fi/~palaste ---------------------规则! -------- /

肯定很有钱和小鸡。

- Beavis和Butt-head



The C standard says that malloc is allowed to allocate more memory than
requested.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"It sure is cool having money and chicks."
- Beavis and Butt-head


在文章< 40 *********************** @ news.syd.swiftdsl.com.a u>

Kevin Torr< ke ******* @ hotmail.com>写道:
In article <40***********************@news.syd.swiftdsl.com.a u>
Kevin Torr <ke*******@hotmail.com> writes:
http:// www。 yep-mm.com/res/soCrypt.c

一般情况下,最好发布实际有问题的代码

(最好是将其缩小到一个有问题的小块,因为它是b / b
,但如果读取netnews

无法跟踪链接,则URL引用可以起作用。 :-)

我的程序中有2个malloc',当我把它们的内容写到屏幕或文件中时,还有4个字符。
据我所知,注册malloc和将信息写入malloc的代码都很可靠。那为什么我的程序会返回另外4个字符?


虽然问题

与malloc()本身无关,但它并不像人们希望的那么坚固。以下是

代码的摘录(引用>照例,尽管我必须自己插入标记

):

// soCrypt 1.0
#include< stdio.h>
#include< stdlib.h>
#include< string.h>
#include< time.h>
// #include< md5.h>


好​​到目前为止,虽然// - 评论特定于C99。你有

包含必要的标题,所以你不需要抛出malloc()的

返回值。

//全局变量

int statCode = 0; //状态代码
int模式; //模式变量(1 = enc,2 = dec)
int i; // Looper变量
int inSize = 0; //输入文件大小
int intRand; // Random int
char tmp_char; //临时字符


其中许多不应该是文件范围的外部链接(全局)

变量,尽管这主要是一种风格问题(至少在这个小的b $ b程序中)。


注意tmp_char的类型为char;在一个典型的PowerPC上,它会保持0到255之间的值,因为那里普通的char

是无符号的。变量inSize是一个普通(带符号)的int,并且至少在[-32767 .. + 32767]范围内具有

(尽管今天大多数系统,

都有一个偶数范围更广,约+/- 20亿)。

char * pMasterKey; //指向主密钥的malloc指针
char * pInputData; // Malloc指向输入数据的指针


向前跳过,我们有:

//读取输入文件

int readFile ()
回复(inFile);
i = 0;
tmp_char ='''';
while(tmp_char!= EOF) )
{
i ++;
tmp_char = getc(inFile);
}
inSize = i-1;


此循环尝试通过调用getc()

来计算文件的大小,直到getc()返回EOF。问题是EOF是某种类型的负数 - 通常为-1,但可能甚至是-2000或某些

这样 - 而tmp_char是一个简单的炭" ;.如果tmp_char无法支持
,则保持值EOF,如果普通字符未签名,则为真;

或者如果EOF小于CHAR_MIN(例如,-2000 vs -128)例如),

循环永远不会终止。


这就是getc()返回类型为int的值的原因。首先,

以便它可以返回所有可能的char(首先将

任何负数转换为正值,就像通过unsigned char一样) ;),

还返回特殊标记值EOF。如果你想存储

两个任何有效字符 *和* EOF,你需要比任何有效字符更宽的范围。


当然,真的不需要tmp_char完全没有

纠正因为在获得一个角色之前计算内部的循环*所产生的一分一秒的错误。只需将循环更改为,

例如:


while(getc(inFile)!= EOF)

i ++;


将此与使用局部变量相结合,也许是一个for>
循环来收集初始化,测试和增量,我们

可能会得到类似的结果:


int readFile(){

int i;


倒带( inFile);

for(i = 0; getc(inFile)!= EOF; i ++)

继续;

inSize = i;


(虽然我也会将FILE *参数传递给readFile,

并且可能返回分配的内存而不是int

状态代码)。

if((pInputData =(char *)malloc(inSize * sizeof(char)))== NULL)
{
statCode = 8;
返回(statCode);
}


这本身就可以,但有两件重要的事情要做

note。首先,不需要演员表。它没有坏处,但也没有帮助。
没有帮助。当tmp_char已经是char时,它有点像说tmp_char =(char)getc(inFile),

。作业将为您进行

转换 - 并且您不使用下面的演员表,那么为什么要使用

以上?


其次,以及之后观察到的问题的实际来源,请注意

,这会分配足够的空间来存储所有字符

您打算从文件中读取。


考虑C字符串hello world。

中有多少个字符呢? *存储*需要多少个字符?为什么,之后:


char hello [] =" hello world" ;;


sizeof hello之间的差异为1 ;和strlen(你好)?


答案是:因为C字符串需要一个''\0''标记,所有

后才有效"炭" S。数组hello []的大小为12,而不是大小为11,因为它存储构成两个单词的11个char和空白的b $ b,以及然后再存储一个''\0''标记。


如果文件内容

是变量inSize可能(例如)保持5 " word\\\
" (可能后跟一个EOF标记,如果你的系统实际上在文件中使用了这样的标记),但如果你想使用

序列{''w'', ''o'','r'','d'',''\ n''}作为C字符串,你需要* six *

bytes:{''w '','''',''r'','''',''\\'n'',''\ 0''}。


当然,没有要求您将文件视为

a C字符串 - 该部分取决于您。在任何情况下:

倒带(inFile);
i = 0;
tmp_char =''a'';
while(i< inSize)
{
tmp_char = getc(inFile);
*(pInputData + i)= tmp_char;
i ++;
}
返回0;
}


这里没有*错*,但代码可以简化

。首先,如果没有首先调用getc(),就不会检查tmp_char,因此不需要启动泵。 -

循环测试i< INSIZE" ;.其次,根本不需要tmp_char

;你可以直接将getc()的值赋给

pInputData [i]。第三,你可以这样写pInputData [i],而不是使用等价的一元 - " *"顺序,再次

也许是for循环可以更好地表达整个序列:


倒带(inFile);

for(i = 0; i< inSize; i ++)

pInputData [i] = getc(inFile);

返回0;

}


跳到观察到的问题的来源:

//写入输出文件

int writeFile()
{
fputs(pInputData,outFile);
fputs(pMasterKey,keyOut);
返回0;
}
http://www.yep-mm.com/res/soCrypt.c
In general, it is better to post the actual problematic code
(preferably after shrinking it down to a "problematic nub", as it
were), but a URL reference can work if the one reading netnews
bothers to follow the link. :-)
I have 2 malloc''s in my program, and when I write the contents of them to
the screen or to a file, there aren addition 4 characters. As far as I can tell, both the code to register the malloc and to write
information into the malloc is solid. Why then ismy program returning an
additional 4 characters?
It is not quite as solid as one might hope, although the problem
has nothing to do with malloc() per se. Here are excerpts from the
code (quoted with ">" as usual, although I had to insert the markers
myself):
// soCrypt 1.0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// #include <md5.h>
OK so far, although //-comments are specific to C99. You have
included necessary headers, so you will not need to cast malloc()''s
return value.
// Global variables

int statCode = 0; // Status code
int mode; // Mode variable (1 = enc, 2 = dec)
int i; // Looper variable
int inSize = 0; // Input filesize
int intRand; // Random int
char tmp_char; // Temporary char
Many of these should not be file-scope external-linkage ("global")
variables, although this is mostly a style issue (at least in a
program this small).

Note that tmp_char has type "char"; on a typical PowerPC, it would
hold values between 0 and 255 inclusive, because there plain "char"
is unsigned. The variable inSize is a plain (signed) int and has
at least the range [-32767..+32767] (although most systems, today,
have an even wider range, about +/- 2 billion).
char *pMasterKey; // Malloc pointer to the master key
char *pInputData; // Malloc pointer to the input data
Skipping forward, we have:
// Reads the input file

int readFile()
{

rewind(inFile);
i = 0;
tmp_char = ''a'';
while(tmp_char != EOF)
{
i++;
tmp_char = getc(inFile);
}
inSize = i-1;
This loop tries to count the size of the file by calling getc()
until getc() returns EOF. The problem is that EOF is some sort of
negative number -- typically -1, but perhaps even -2000 or some
such -- and tmp_char is a plain "char". If tmp_char is unable to
hold the value EOF, which will be true if plain char is unsigned
or if EOF is less than CHAR_MIN (e.g., -2000 vs -128 for instance),
the loop will never terminate.

This is why getc() returns a value of type "int" in the first place,
so that it can return all possible "char"s (having first converted
any negative ones to positive values as if via "unsigned char"),
yet also return the special marker value EOF. If you want to store
both "any valid character" *and* EOF, you need something with a
wider range than "any valid character".

Of course, there is really no need for tmp_char at all, nor for
correcting for the off-by-one error produced by counting inside
the loop *before* getting a character. Just change the loop to,
e.g.:

while (getc(inFile) != EOF)
i++;

Combine this with using local variables, and perhaps a "for"
loop to collect up the initialization, test, and increment, we
might get something like:

int readFile() {
int i;

rewind(inFile);
for (i = 0; getc(inFile) != EOF; i++)
continue;
inSize = i;

(although I would also pass the "FILE *" parameter to readFile,
and probably return the allocated memory rather than an "int"
status code).
if ((pInputData = (char *)malloc(inSize * sizeof(char))) == NULL)
{
statCode = 8;
return(statCode);
}
This is OK in and of itself, but there are two important things to
note. First, the cast is not required. It does no harm, but also
does no help. It is a bit like saying "tmp_char = (char)getc(inFile)",
when tmp_char is already a char. The assignment will do the
conversion for you -- and you do not use a cast below, so why use
one above?

Second, and the actual source of the observed problem later, note
that this allocates just enough space to store all the characters
you intend to read from the file.

Consider the C string "hello world". How many characters are in
it? How many characters does it take to *store* it? Why, after:

char hello[] = "hello world";

is there a difference of 1 between "sizeof hello" and "strlen(hello")?

The answer is: because C strings require a ''\0'' marker after all
their valid "char"s. The array hello[] has size 12, not size 11,
because it stores the 11 "char"s that make up the two words and
the blank, and then one more to store the ''\0'' marker.

The variable inSize might (for instance) hold 5 if the file contents
are "word\n" (perhaps followed by an EOF marker, if your system
actually uses such markers in files), but if you want to use the
sequence {''w'', ''o'', ''r'', ''d'', ''\n''} as a C string, you need *six*
bytes: {''w'', ''o'', ''r'', ''d'', ''\n'', ''\0''}.

Of course, there is no requirement that you treat the file as
a C string -- that part is up to you. In any case:
rewind(inFile);
i = 0;
tmp_char = ''a'';
while (i < inSize)
{
tmp_char = getc(inFile);
*(pInputData + i) = tmp_char;
i++;
}
return 0;
}
There is nothing *wrong* here, but the code can be simplified
enormously. First, tmp_char is never inspected without first
calling getc(), so there is no need to "prime the pump" -- the
loop tests "i < inSize". Second, there is no need for tmp_char
at all; you can just assign the value from getc() directly into
pInputData[i]. Third, you can write pInputData[i] that way,
rather than using the equivalent unary-"*" sequence, and again
perhaps a "for" loop might express the whole sequence better:

rewind(inFile);
for (i = 0; i < inSize; i++)
pInputData[i] = getc(inFile);
return 0;
}

Skipping forward to the source of the observed problem:
// Writes the output file

int writeFile()
{
fputs(pInputData, outFile);
fputs(pMasterKey, keyOut);
return 0;
}




fputs()函数需要一个字符串 - 一个序列" char" s
以''\ 0''结束标记结尾。 pInputData指向char序列中的第一个

,而不是指向停止此处

在\0中的一个。在其中标记。


如果不做任何其他更改,您可以分配一个额外的

字节并输入''\0'',或者你可以改变你使用的方法

写出最终输出。这两个人只需要同意

pInputData(和pMasterKey - 但我甚至没看过那段代码)

是一个计数字符串(长度inSize,for pInputData)或C风格

''\''' - 终止字符串。


注意''\ 0'' - 终止string不能*包含* a''\''',所以如果你想要(无论出于什么原因)允许嵌入''\ 0''字节,你需要

必须选择count-string方法。你可以写一个带循环的计数字符串




int writeFile(){

int i;


for(i = 0; i< inSize; i ++)

putc(pInputData [i],outFile);

/ *可选:

if(fflush(outFile)|| ferror(outFile))

...处理输出失败... * /

/ *并重复pMasterKey * /

}


或者你可以使用fwrite(),它基本上为你做了循环。

(请注意,fwrite()在普通文本中运行得很好,并且在

中,fputs()可以在内部实现为:


int fputs(char * s,FILE * stream){

size_t len = strlen(s);


返回fwrite(s,1,len,stream) == len?0:EOF;

}


这里strlen()查找,但不计算,终止''\0'' ,

然后fwrite()循环遍历所有有效字节,putc()每一个

到流。唯一剩下的问题我来自fwrite()的返回值

与来自fputs()的返回值不一致,因此必须转换为
。)

-

In-Real-Life:风河系统Chris Torek

美国犹他州盐湖城(40°39.22''N,111°50.29'' W)+1 801 277 2603

电子邮件:忘了它 http://web.torek.net/torek/index.html

由于垃圾邮件发送者,阅读电子邮件就像在垃圾中搜索食物一样。



The fputs() function demands a string -- a sequence of "char"s
ending with a ''\0'' termination marker. pInputData points to the
first of a sequence of "char"s, but not one that has the "stop here
at the \0" mark in it.

Without making any other changes, you can either allocate one extra
byte and put in the ''\0'', or you can change the method you use to
write the final output. The two simply have to agree as to whether
pInputData (and pMasterKey -- but I did not even look at that code)
is a counted string (length inSize, for pInputData) or a C-style
''\0''-terminated string.

Note that a ''\0''-terminated string cannot *contain* a ''\0'', so if
you want (for whatever reason) to allow embedded ''\0'' bytes, you
will have to choose the counted-string method. You could write
out a counted string with a loop:

int writeFile() {
int i;

for (i = 0; i < inSize; i++)
putc(pInputData[i], outFile);
/* optional:
if (fflush(outFile) || ferror(outFile))
... handle output failure ... */
/* and repeat for pMasterKey */
}

or you can use fwrite(), which essentially does the loop for you.
(Note that fwrite() works just fine with ordinary text, and in
fact, fputs() can be implemented internally as:

int fputs(char *s, FILE *stream) {
size_t len = strlen(s);

return fwrite(s, 1, len, stream) == len ? 0 : EOF;
}

Here strlen() looks for, but does not count, the terminating ''\0'',
then fwrite() loops over all the valid bytes, putc()ing each one
to the stream. The only remaining problem is that the return value
from fwrite() does not match that from fputs(), so it has to be
converted.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22''N, 111°50.29''W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.


" Chris Torek" <无**** @ torek.net>在消息中写道

news:c4 ********* @ news2.newsguy.com ...
"Chris Torek" <no****@torek.net> wrote in message
news:c4*********@news2.newsguy.com...
在文章< 40 ***** ******************@news.syd.swiftdsl.com.a u>
Kevin Torr< ke ******* @ hotmail.com> ;写道:
In article <40***********************@news.syd.swiftdsl.com.a u>
Kevin Torr <ke*******@hotmail.com> writes:
http:// www。 yep-mm.com/res/soCrypt.c



一般情况下,最好发布实际有问题的代码
(最好是将其缩小到一个有问题的小块,因为它是



In general, it is better to post the actual problematic code
(preferably after shrinking it down to a "problematic nub", as it
were), but a URL reference can work if the one reading netnews
bothers to follow the link. :-)

我的程序中有2个malloc',当我把它们的内容写到屏幕或文件中时,还有4个字符。
I have 2 malloc''s in my program, and when I write the contents of them to
the screen or to a file, there aren addition 4 characters.


据我所知,注册malloc和将信息写入malloc的代码都是可靠的。那为什么我的程序会返回另外4个字符?
As far as I can tell, both the code to register the malloc and to write
information into the malloc is solid. Why then ismy program returning an
additional 4 characters?



它不像人们希望的那么坚固,虽然问题
与malloc无关()本身。以下是
代码的摘录(通常用>引用,虽然我必须自己插入标记
):



It is not quite as solid as one might hope, although the problem
has nothing to do with malloc() per se. Here are excerpts from the
code (quoted with ">" as usual, although I had to insert the markers
myself):

// soCrypt 1.0
#include< stdlib.h>
#include< string.h>
#include< time.h>
// #include< md5.h>
// soCrypt 1.0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// #include <md5.h>



好了到目前为止,虽然// - 评论特定于C99。你已经包含了必要的标题,所以你不需要强制转换malloc()的返回值。



OK so far, although //-comments are specific to C99. You have
included necessary headers, so you will not need to cast malloc()''s
return value.

//全局变量

int statCode = 0; //状态代码
int模式; //模式变量(1 = enc,2 = dec)
int i; // Looper变量
int inSize = 0; //输入文件大小
int intRand; // Random int
char tmp_char; // Temporary char
// Global variables

int statCode = 0; // Status code
int mode; // Mode variable (1 = enc, 2 = dec)
int i; // Looper variable
int inSize = 0; // Input filesize
int intRand; // Random int
char tmp_char; // Temporary char



其中许多不应该是文件范围的外部链接(全局)变量,尽管这主要是一个样式问题(至少在这个小的程序中。

请注意,tmp_char的类型为char;在一个典型的PowerPC上,它将保持0到255之间的值,因为普通的char
是无符号的。变量inSize是一个普通(带符号)int并且至少具有范围[-32767 .. + 32767](尽管大多数系统,今天,
具有更宽的范围,大约+/- 2亿元)。



Many of these should not be file-scope external-linkage ("global")
variables, although this is mostly a style issue (at least in a
program this small).

Note that tmp_char has type "char"; on a typical PowerPC, it would
hold values between 0 and 255 inclusive, because there plain "char"
is unsigned. The variable inSize is a plain (signed) int and has
at least the range [-32767..+32767] (although most systems, today,
have an even wider range, about +/- 2 billion).

char * pMasterKey; //指向主密钥的malloc指针
char * pInputData; // Malloc指向输入数据的指针
char *pMasterKey; // Malloc pointer to the master key
char *pInputData; // Malloc pointer to the input data



向前跳过,我们有:



Skipping forward, we have:

//读取输入文件

int readFile()
回复(inFile);
i = 0;
tmp_char =''a'';
while( tmp_char!= EOF)
{
i ++;
tmp_char = getc(inFile);
}
inSize = i-1;
// Reads the input file

int readFile()
{

rewind(inFile);
i = 0;
tmp_char = ''a'';
while(tmp_char != EOF)
{
i++;
tmp_char = getc(inFile);
}
inSize = i-1;



此循环尝试通过调用getc()
来计算文件的大小,直到getc()返回EOF。问题是EOF是某种负数 - 通常是-1,但可能甚至是-2000或某些
这样 - 而tmp_char是一个简单的char。如果tmp_char无法保持值EOF,如果普通字符未签名或者EOF小于CHAR_MIN(例如,-2000 vs -128),则为真,
循环永远不会终止。

这就是getc()返回类型为int的值的原因。首先,
以便它可以返回所有可能的char(首先将任何负面的值转换为正值,就像通过unsigned char一样),
还返回特殊标记值EOF。如果你想存储两个任何有效字符, *和* EOF,你需要比任何有效字符更宽范围的东西。

当然,根本不需要tmp_char,也不需要
纠正在获取角色之前通过计数内部循环*产生的逐个错误。只需将循环更改为,
例如:

while(getc(inFile)!= EOF)
i ++;

将此与使用局部变量相结合,也许是一个for循环来收集初始化,测试和增量,我们可能会得到类似的结果:

int readFile(){
int i;

倒带(inFile);
for(i = 0; getc(inFile)!= EOF; i ++)
继续;
inSize = i ;

(虽然我也会将FILE *参数传递给readFile,
并且可能返回分配的内存而不是int状态代码) 。



This loop tries to count the size of the file by calling getc()
until getc() returns EOF. The problem is that EOF is some sort of
negative number -- typically -1, but perhaps even -2000 or some
such -- and tmp_char is a plain "char". If tmp_char is unable to
hold the value EOF, which will be true if plain char is unsigned
or if EOF is less than CHAR_MIN (e.g., -2000 vs -128 for instance),
the loop will never terminate.

This is why getc() returns a value of type "int" in the first place,
so that it can return all possible "char"s (having first converted
any negative ones to positive values as if via "unsigned char"),
yet also return the special marker value EOF. If you want to store
both "any valid character" *and* EOF, you need something with a
wider range than "any valid character".

Of course, there is really no need for tmp_char at all, nor for
correcting for the off-by-one error produced by counting inside
the loop *before* getting a character. Just change the loop to,
e.g.:

while (getc(inFile) != EOF)
i++;

Combine this with using local variables, and perhaps a "for"
loop to collect up the initialization, test, and increment, we
might get something like:

int readFile() {
int i;

rewind(inFile);
for (i = 0; getc(inFile) != EOF; i++)
continue;
inSize = i;

(although I would also pass the "FILE *" parameter to readFile,
and probably return the allocated memory rather than an "int"
status code).

if((pInputData =(char *)malloc(inSize * sizeof(char)))== NULL)
{
statCode = 8;
return(statCode);
}
if ((pInputData = (char *)malloc(inSize * sizeof(char))) == NULL)
{
statCode = 8;
return(statCode);
}



这本身就可以,但有两个重要的事情要注意。首先,不需要演员表。它没有坏处,但也没有帮助。这有点像说tmp_char =(char)getc(inFile),
当tmp_char已经是char时。作业将为你做转换 - 你不使用下面的演员,那么为什么要使用上面的一个?

第二,观察的实际来源问题稍后,请注意,这会分配足够的空间来存储您打算从文件中读取的所有字符。

考虑C字符串hello world。
中有多少个字符? *存储*需要多少个字符?为什么,之后:

char hello [] =" hello world" ;;

sizeof hello之间的差异为1答案是:strlen(hello)?

答案是:因为C字符串在所有
有效的char之后需要一个''\0''标记。数组hello []的大小为12,而不是大小为11,因为它存储构成两个单词的11个char和空白,然后再存储一个'' \'''标记。

如果文件内容
是word \ n,变量inSize可能(例如)保持5。 (如果你的系统实际上在文件中使用了这样的标记,可能会跟着一个EOF标记),但如果你想使用
序列{''w'',''o'','' r'','d'',''\ n''}作为C字符串,你需要* six *
字节:{''w'',''o'',''r '','''',''\ n'',''\ 0''}。

当然,没有要求您将文件视为
一个C字符串 - 该部分取决于您。在任何情况下:



This is OK in and of itself, but there are two important things to
note. First, the cast is not required. It does no harm, but also
does no help. It is a bit like saying "tmp_char = (char)getc(inFile)",
when tmp_char is already a char. The assignment will do the
conversion for you -- and you do not use a cast below, so why use
one above?

Second, and the actual source of the observed problem later, note
that this allocates just enough space to store all the characters
you intend to read from the file.

Consider the C string "hello world". How many characters are in
it? How many characters does it take to *store* it? Why, after:

char hello[] = "hello world";

is there a difference of 1 between "sizeof hello" and "strlen(hello")?

The answer is: because C strings require a ''\0'' marker after all
their valid "char"s. The array hello[] has size 12, not size 11,
because it stores the 11 "char"s that make up the two words and
the blank, and then one more to store the ''\0'' marker.

The variable inSize might (for instance) hold 5 if the file contents
are "word\n" (perhaps followed by an EOF marker, if your system
actually uses such markers in files), but if you want to use the
sequence {''w'', ''o'', ''r'', ''d'', ''\n''} as a C string, you need *six*
bytes: {''w'', ''o'', ''r'', ''d'', ''\n'', ''\0''}.

Of course, there is no requirement that you treat the file as
a C string -- that part is up to you. In any case:

倒带(inFile);
i = 0;
tmp_char =''a'';
while(i< inSize)
{
tmp_char = getc(inFile);
*(pInputData + i)= tmp_char;
i ++;
}
返回0;
}
rewind(inFile);
i = 0;
tmp_char = ''a'';
while (i < inSize)
{
tmp_char = getc(inFile);
*(pInputData + i) = tmp_char;
i++;
}
return 0;
}



这里没有*错误*,但代码可以简化得非常简单。首先,如果没有首先调用getc(),就不会检查tmp_char,因此不需要启动泵。 -
循环测试i< INSIZE" ;.其次,根本不需要tmp_char
;你可以直接将getc()的值赋给
pInputData [i]。第三,你可以用那种方式写pInputData [i],而不是使用等价的一元 - " *"顺序,再一次
也许是for循环可以更好地表达整个序列:

倒带(inFile);
for(i = 0; i< inSize; i ++)
pInputData [i] = getc(inFile );
返回0;
}

跳到观察到的问题的来源:



There is nothing *wrong* here, but the code can be simplified
enormously. First, tmp_char is never inspected without first
calling getc(), so there is no need to "prime the pump" -- the
loop tests "i < inSize". Second, there is no need for tmp_char
at all; you can just assign the value from getc() directly into
pInputData[i]. Third, you can write pInputData[i] that way,
rather than using the equivalent unary-"*" sequence, and again
perhaps a "for" loop might express the whole sequence better:

rewind(inFile);
for (i = 0; i < inSize; i++)
pInputData[i] = getc(inFile);
return 0;
}

Skipping forward to the source of the observed problem:

//写入输出文件

int writeFile()
{/> fputs(pInputData,outFile);
fputs(pMasterKey,keyOut);
返回0;
}
// Writes the output file

int writeFile()
{
fputs(pInputData, outFile);
fputs(pMasterKey, keyOut);
return 0;
}



fputs()函数需要一个字符串 - 一系列char,以''\ 0''终止标记结尾。 pInputData指向char序列中的第一个,但不是指在\ 0中具有在此处停止的那个。在其中进行标记。

不做任何其他更改,您可以分配一个额外的
字节并放入''\0'',或者您可以更改您使用的方法
写出最终输出。两者只需要同意是否pInputData(和pMasterKey - 但我甚至没看过那段代码)
是一个计数字符串(长度为inSize,对于pInputData)或C风格
''\''' - 终止字符串。

请注意,''\ 0'' - 终止字符串不能*包含* a''\ 0'',所以如果
你想(无论出于何种原因)允许嵌入''\ 0''字节,你必须选择count-string方法。你可以写一个带循环的计数字符串:

int writeFile(){
int i;

for(i = 0; i < inSize; i ++)
putc(pInputData [i],outFile);
/ *可选:
if(fflush(outFile)|| ferror(outFile))
。 ..处理输出失败... * /
/ *并重复pMasterKey * /
}

或者你可以使用fwrite(),它基本上为你做了循环。
(注意,fwrite()在普通文本中运行得很好,而且事实上,fputs()可以在内部实现为:

int fputs(char * s, FILE * stream){
size_t len = strlen(s);

返回fwrite(s,1,len,stream)== len?0:EOF;
}

这里strlen()查找,但不计算,终止''\ 0'',然后fwrite()遍历所有有效字节,putc()每个
到流。唯一剩下的问题是来自fwrite()的返回值
与fputs()不匹配,因此必须进行转换。)



The fputs() function demands a string -- a sequence of "char"s
ending with a ''\0'' termination marker. pInputData points to the
first of a sequence of "char"s, but not one that has the "stop here
at the \0" mark in it.

Without making any other changes, you can either allocate one extra
byte and put in the ''\0'', or you can change the method you use to
write the final output. The two simply have to agree as to whether
pInputData (and pMasterKey -- but I did not even look at that code)
is a counted string (length inSize, for pInputData) or a C-style
''\0''-terminated string.

Note that a ''\0''-terminated string cannot *contain* a ''\0'', so if
you want (for whatever reason) to allow embedded ''\0'' bytes, you
will have to choose the counted-string method. You could write
out a counted string with a loop:

int writeFile() {
int i;

for (i = 0; i < inSize; i++)
putc(pInputData[i], outFile);
/* optional:
if (fflush(outFile) || ferror(outFile))
... handle output failure ... */
/* and repeat for pMasterKey */
}

or you can use fwrite(), which essentially does the loop for you.
(Note that fwrite() works just fine with ordinary text, and in
fact, fputs() can be implemented internally as:

int fputs(char *s, FILE *stream) {
size_t len = strlen(s);

return fwrite(s, 1, len, stream) == len ? 0 : EOF;
}

Here strlen() looks for, but does not count, the terminating ''\0'',
then fwrite() loops over all the valid bytes, putc()ing each one
to the stream. The only remaining problem is that the return value
from fwrite() does not match that from fputs(), so it has to be
converted.)




哇,谢谢为了这一切。我将不得不全神贯注。


那么我什么时候不需要投射mallocs?当我包括标题?哪个标题?

或者你是说我已经定义了

指针作为数据类型,我不需要投一个malloc吗? />
如果我在不需要

的情况下投出malloc,那会是什么可能的坏事?有什么东西可能出错或者是多余的吗?



Wow, thanks for all that. I will have to get my head around it all.

So when do I need not cast mallocs? when I include a header? which header?
Or are you saying that I don''t need to cast a malloc if I''ve already defined
the pointer as a data type?
What would be a possible bad thing if I did cast a malloc when I didn''t need
to? Is there something that could go wrong or is it just redundant?


这篇关于malloc + 4 ??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆