Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Memory corruption on freeing a pointer to pointer
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
Reply to thread
Message
[QUOTE="gdotone, post: 5113089"] /* This program creates and uses pointers to pointer of type char, pointer to arrays of char, malloc(), to allocate memory for the pointer to pointer and 1-D arrays, strlen(), sizeof(), and strtok(). Using those functions the program separates words, in array of character arrays, and string constants. It places those words in an allocated spaces. This program builds from simple statements and ideas so not to overwhelm. */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main( void ) { char **a; int numberOfPointers = 5; a = (char **) malloc ( numberOfPointers * ( sizeof(char * ) ) ); if ( a!= NULL ) printf( "the array, a, points to declare space\n\n" ); char *b[] = { "one", "two", "three", "four", "five" }; a = b; for ( int index = 0; index < 5; index++ ) { printf( "%s\n\n", *(a+index) ); } for ( int index = 0; index < 5; index++ ) { printf( "%s\n\n", *(a+index) ); } char *string = "word" ; size_t n = strlen( string ); printf("\n %zd \n\n", n); /* %zd because n is of type size_t */ char sentence[] = "this is a sentence with words"; char *token = " "; char *g; g = strtok(sentence, token); size_t y = strlen(g); printf("the length of the first word in the sentence is %d\n\n", (int) y ); char *c_space = (char *) malloc( y * sizeof(char) + 1 ); if (c_space) { printf("got space for word\n\n"); } int indexnewstring = (int) y + 1; /* (int) strlen( g ) + 1 */ char newstring[indexnewstring]; char *v = strcpy( newstring, g); printf(" %s\n", v ); char sentence2[] = "this is a sentence with words"; g = strtok( sentence2, token ); while ( g != NULL ) { printf("\n %s", g ); g = strtok( NULL, token ); } printf("\n"); char sentence3[] = "C programming actually is the fun"; for( g = strtok(sentence3, token ); g != NULL; g = strtok( NULL, token ) ) printf (" %s\n", g ); return 0; } Questions: How do you free a pointer to a pointer of what it points to? How would you free the pointer of the pointer a. (a+index)? strtok(), on my machine, seems to only take an array of characters. Is the function suppose to string constants too. sen4 = {"this is a short sentence"}; ken i hope this posting is better. let me know. thanks. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Memory corruption on freeing a pointer to pointer
Top