This code snippet
char* chaine = malloc(sizeof(char)*10);
chaine = "ouii";
results in a memory leak.
At first a memory was allocated dynamically and its address was assigned to the pointer chaine
char* chaine = malloc(sizeof(char)*10);
and then the pointer was reassigned with the address of the first character of the string literal "ouii"
chaine = "ouii";
So the address of the dynamically allocated memory was lost.
Instead of this assignment
chaine = "ouii";
you need to copy characters of the string literal into the dynamically allocated memory using standard string function strcpy
declared in the header <string.h>
. For example
#include <string.h>
//...
char* chaine = malloc(sizeof(char)*10);
strcpy( chaine, "ouii" );
Pay attention to that this function
void supprimer(myStruct* D) {
free(D->chaine);
free(D);
}
makes the pointer D
declared in main
myStruct* D = malloc(sizeof(myStruct));
invalid.
It is better to pass the pointer to the function by reference.
In C passing by reference means passing an object (including pointers) indirectly through a pointer to it. Thus dereferencing the pointer you will have a direct access to the object pointed to by the pointer and can change it.
Also as it seems you want to define a singly linked list then the function can look the following way
void supprimer( myStruct **D )
{
while ( *D != NULL )
{
myStruct *current = *D;
*D = ( *D )->next;
free( current->chaine );
free( current );
}
}
And the function is called like
supprimer( &D );
In this case after calling the function the pointer D
defined in main will be equal to NULL
.
Pay attention to that you should check whether memory was allocated successfully to avoid undefined behavior.
Here is a demonstration program that shows how your list could be implemented.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct myStruct
{
char *chaine;
struct myStruct *next;
} mystruct;
int push ( myStruct **D, const char *chaine )
{
myStruct *current = malloc( sizeof( *current ) );
int success = current != NULL;
if (success)
{
current->chaine = malloc( strlen( chaine ) + 1 );
success = current->chaine != NULL;
if (success)
{
strcpy( current->chaine, chaine );
current->next = *D;
*D = current;
}
else
{
free( current );
}
}
return success;
}
void supprimer( myStruct **D )
{
while (*D != NULL)
{
myStruct *current = *D;
*D = ( *D )->next;
free( current->chaine );
free( current );
}
}
void output( const myStruct *D )
{
for ( const myStruct *current = D; current != NULL; current = current->next )
{
printf( "\"%s\" -> ", current->chaine );
}
puts( "null" );
}
int main( void )
{
myStruct *D = NULL;
push( &D, "World" );
push( &D, "Hello" );
output( D );
supprimer( &D );
}
The program output is
"Hello" -> "Word" -> null