Re: string in an array



My doubt comes when declaring a array bigger than the string it is
going to be stored inside it:

char* array = malloc( sizeof(char)*1024 );

The variable named 'array' is a *POINTER*, not an array.

strcpy( array, "hello" );


When comes to free it, I always supposed that the entire array is
freed.
But today, using the (non compliant) mode to check the size of an
array:
sizeof(array) / sizeof(array[0])

This doesn't work when applied to a (char *) pointer. You get the
size of a (char *) pointer. On what machine is the size of a pointer
equal to sizeof("hello")?

I noticed that the size I get is the size of "hello" and not 1024
bytes (I repeat, I know this is not the best way to check an array's
size). I'm not sure if free() is going to free strlen("hello") bytes
or the full 1024.

It works fine on an array, but you are not giving it an array.

The way to keep track of the size of a piece of memory allocated
with malloc() or friends calloc() or realloc() is to remember how
much you allocated in the first place.

This doubts are related to deleting (freeing) the source string I pass
to a function like strtok(), which is going to modify it.

Could someone clear my mind?

free() frees memory allocated by one call to malloc() or friends,
regardless of the contents of the memory. It is not possible to
free() *part of* the memory allocated by one call to malloc() or
friends.
--
comp.lang.c.moderated - moderation address: clcm@xxxxxxxxxxxx -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
.



Relevant Pages

  • Re: Malloc code
    ... malloc() not return NULL? ... returned from malloc to an array of pointers, and then return this array of ... So I just returned a void pointer and assign the value to ... TCP_LOAD_MCB_X and I am assigning the values to the items of the strucutre ...
    (microsoft.public.vc.language)
  • Re: Can array[]=malloc()ed?
    ... > int main ... > in the above I have used array but derefered as a pointer since ... > first element in a array I wanted to malloc the array y. ...
    (comp.lang.c)
  • Re: char **argv & char *argv[]
    ... "pointer to pointer to char". ... >> pointer)) pointing to the first element of an array. ... so we have to start adding more context. ... type "pointer to char", rather than "array MISSING_SIZE of char". ...
    (comp.lang.c)
  • Re: Can array[]=malloc()ed?
    ... >> int main ... >> in the above I have used array but derefered as a pointer since ... >> first element in a array I wanted to malloc the array y. ...
    (comp.lang.c)
  • Re: Casting a generic or void pointer to point to a struct...
    ... that what I really need is known in C as a "dynamic array". ... with malloc() or calloc. ... would use to cast a gneeric or void pointer to a struct that I have ... memory obtained with the calloc() function. ...
    (comp.lang.c)