|
From: Iuri K. <IK...@am...> - 2001-07-18 17:46:06
|
Dear Luigi, Thank you for your help. I tried to use calloc because de string read from the file string has diferent sizes. I.e. the first line of the file script = is "iuri", when I write: fgets (linha1_ptr ,sizeof(linha1_ptr), script); It returns: iur If I write: fgets (linha1_ptr , 30 , script); It returns: iuri With static memory the problem is that it reads the hole thing: So if my string is: aaaaaaaaaa bbbb With the fgets it will read: aaaaaaaaaa bbbb\0aaaa I think with sizeof it shouldn't happen, but it does. He reads the size = of the 1=BA line and returns this same size for every line, even if it's bigger. Thanks, Iuri Date: Tue, 17 Jul 2001 19:46:44 +0200 To: dev...@li... From: Luigi Santillo <gi...@li...> Subject: Re: [Dev-C++] Malloc Problem Reply-To: dev...@li... In a C program you can ask for memory in a "static fashion" (i.e. at=20 compile time) and in a "dynamic fashion" (i.e. at execution time). When you define "linha1" by the line: char linha1[31]; /* 1 is for the terminating '\0' */ you are using static memory, this means that linha1 will be made of 30=20 chars during the whole execution, and its size is known at compile = time. If you wish to use dynamic memory, then I suggest you use calloc = instead of=20 malloc (calloc is for arrays) char *linha1; ... linha1 =3D (char *)calloc(31, sizeof(char)); /* 1 is for the = terminating '\0' */ When you no longer need the dynamically allocated variable linha1, you=20 should release the memory by the following: free(linha1); Dynamic memory is used when the size of the string is not known in = advance,=20 since in your code, you already know that no string has more than 30 = chars,=20 you should use static memory. In my opinion your code should be: --- #define MAX_SIZE 31 char linha1[MAX_SIZE]; ... fgets(linha1, MAX_SIZE, script); ... --- At 12.51 17/07/01 -0300, you wrote: >I can't find any tutorial about Malloc for strings. >I want to read a string (line) from a file named 'script'. Each line = has=20 >one string with diferent size. >The MAX string will have 30 chars. >I know it is very simple, but I can't find the solution. > Thanks, > Iuri >--------- > char linha1 [30]; > char *linha1_ptr =3D linha1; > linha1_ptr =3D malloc (30); >... > fgets (linha1_ptr , sizeof(linha1_ptr) , script); > printf(linha1_ptr,"\n"); > fputs(linha1_ptr, tudo); > write(sockfd, linha1_ptr, sizeof(linha1_ptr)); > write(sockfd, "\n\r",2); >------------ --- gisan --__--__-- |