Return a string on C -



Return a string on C -

i'm getting core dump have no clue how solve. have searched other questions , googled problem can't figure out how solve this...

here code:

const char checkextension(const char *filename) { const char *point = filename; const char *newname = malloc(sizeof(filename-5)); if((point = strrchr(filename,'.palz')) != null ) { if(strstr(point,".palz") == 0) { strncpy(newname, filename, strlen(filename)-5); printf("%s\n",newname ); // name shows correctly homecoming newname; // segmentation fault (core dumped) } } homecoming point; }

the function called char checkextensions(const char *filename). added const due solutions have found online far haven't been able create work... give thanks in advance help!

you have many problems code. here of them:

your function returns char single character. need homecoming pointer array of characters, c string. you don't allocate right amount of memory. utilize sizeof() on pointer yields size of pointer. you create impossible caller know whether or not deallocate memory. heap allocate, not. approach leak. you pass '.palz', character literal, strrchr expects single char. mean pass '.'.

a improve approach allow caller allocate memory. here finish programme shows how:

#include <string.h> #include <stdio.h> void getnewfilename(const char *filename, char *newfilename) { const char *dot = strrchr(filename, '.'); if (dot) { if (strcmp(dot, ".palz") == 0) { size_t len = dot - filename; memcpy(newfilename, filename, len); newfilename[len] = 0; return; } } size_t len = strlen(filename); memcpy(newfilename, filename, len); newfilename[len] = 0; return; } int main(void) { char filename[256]; char newfilename[256]; strcpy(filename, "foo.bar"); getnewfilename(filename, newfilename); printf("%s %s\n", filename, newfilename); strcpy(filename, "foo.bar.palz"); getnewfilename(filename, newfilename); printf("%s %s\n", filename, newfilename); strcpy(filename, "foo.bar.palz.txt"); getnewfilename(filename, newfilename); printf("%s %s\n", filename, newfilename); homecoming 0; }

output

foo.bar foo.bar foo.bar.palz foo.bar foo.bar.palz.txt foo.bar.palz.txt

note strcmp compares sensitive letter case. on windows file names insensitive case. leave issue deal with.

by letting caller allocate memory allow them chose memory allocated. can utilize local stack allocated buffer if like. , it's easy caller allocate memory because new file name never longer original file name.

c string segmentation-fault return

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -