Jak zwolnić blok pamięci zalokowany przez malloc()?

0

jak w temacie

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>

int main()
{
    const char * test[] =  {
        "007", "AS504M", "as", "2147483647iNT", "unsigned4294967295long",
        "922337203long long6854775807", "unsigned184long467440737long09551615",
        "Wow99999999999999999999999999999999999999999999", "00Os9Yeah20"
    };

    int test_size = ((unsigned)(sizeof(test) / sizeof(test[0]) ) );
    for(int i=0; i<test_size; ++i)
    {
        printf("str: %s\n",test[i]);
        int size = strlen(test[i]);
        const char *tmp = test[i];
        char *t = (char *)malloc(sizeof(char)*size);
        if(t == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        for(int i=0, j=0; i<strlen(tmp); ++i) {
            if(tmp[i]>='0' && tmp[i]<='9'){
            //if(isdigit(tmp[i])){
                t[j]=tmp[i];
                ++j;
            }
        }
        printf("str: %s\n",t);
        unsigned long ul = strtoul(t, &t, 10);
        if(ul==ULONG_MAX) {
            printf("num: overflow\n");
        } else {
            printf("num: %ld\n", ul);
        }
        printf("\n");
        free(*t); // How Free a block allocated by 'malloc'
    }

    printf("\n\n");
    return 0;
}
3

free(t);
Z tym że nie potrzebujesz tego malloc()/free()
https://4programmers.net/Forum/C_i_C++/363376-wyszukiwanie_liczby_w_tekscie?p=1866458#id1866458

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    const char *test[]= 
	{
        "007", "AS504M", "as", "2147483647iNT", "unsigned4294967295long",
        "922337203long long6854775807", "unsigned184long467440737long09551615",
        "Wow99999999999999999999999999999999999999999999", "00Os9Yeah20",
    };
    const char *format[]={"%llu","not found","overflow",};

    const size_t test_size=sizeof(test)/sizeof(*test);
    for(size_t t=0;t<test_size;++t)
    {
        unsigned long long value=0;
        const char *str=test[t];
        int none=1;
        printf("str: \"%s\" -> num: ",str);
        for(size_t i=0;str[i];++i)
        {
        	char ch=str[i];
        	if(isdigit(ch))
			{
				unsigned long long next=value*10+(ch-'0');
				if(next>=value)
				{
					none=0;
					value=next;
				}
				else
				{
					none=2;
					break;
				}				
			}
		}
        printf(format[none],value);
        printf("\n");
    }
    return 0;
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1